How to center the absolutely positioned element in div using CSS ?
In this article, we will know how to centre the absolutely positioned element using the <div> tag in CSS, & will understand their implementation through the examples. Sometimes we need to place an element into the centre with absolute position, relative to its nearest positioned ancestor in HTML to make it look more presentable. For centring an absolute positioned element in div we use the following examples.
Example 1: This example demonstrates the centring of an absolute positioned element using the <div> tag.
HTML
<!DOCTYPE html> < html > < head > < style > #content { position: absolute; left: 50%; transform: translateX(-50%) } </ style > </ head > < body > < div id = "content" > < img src = </ div > </ body > </ html > |
Output: Here, the left is given 50% to place it in the centre horizontal. Transform is used to pull back the item with half of its width to place it exactly in the centre from the middle of the element. left: 50% is relative to the parent element while the translate transform is relative to the elements width/height.
Example 2: This example demonstrates the centring of the absolutely positioned element in horizontal & vertical directions in the <div> tag.
HTML
<!DOCTYPE html> < html > < head > < style > .content { height: 400px; position: relative; border: 4px solid green; } .content img { margin: 0; position: absolute; top: 50%; left: 50%; -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); } </ style > </ head > < body > < p > Centering an absolute positioned element inside a div both horizontally and vertically </ p > < div class = "content" > < img src = </ div > </ body > </ html > |
Output: Here left and the top is given 50% to place it in the centre horizontally and vertically. Transform is used to pull back the item with half of its width to place it exactly in the centre from the middle of the element. Therefore transform: translate is given -50% for both horizontal and vertical to adjust it centrally.