I have an absolutly positioned element with content inside. It can be a <h1>
or a few <p>
tag. So I don't know the height of the content.
How can I vertically center the content inside the absolutly positioned div
?
HTML :
<div id="absolute">
<div class="centerd">
<h1>helo</h1>
<span>hi again</span>
</div>
</div>
CSS :
#absolute {
position:absolute;
top:10px;
left:10px;
width:50%;
height:50%;
background:yellow;
}
.centerd {
display:table-cell;
vertical-align:middle;
}
Fiddle
The element with the position: absolute CSS property is positioned relative to its nearest ancestor. We can also align the absolute positioned div element within the center by specifying the CSS property left along with the position: absolute property. The CSS left property will work only when we have already specified the position property.
Centering an absolutely positioned element is a CSS challenge that occurs now and then. The solution seems obvious once I’ve done it, but I still find myself googling the problem every few months. Horizontally centering a static element in CSS is normally handled by setting the left and right margins to auto, for example:
In the end, we want to present a way of centering the content within a <div> both horizontally and vertically. Here, besides the justify-content and display (with "flex") properties, you need the align-items property which will set the vertical alignment to the center.
However, this won’t work on an absolutely positioned element. Its location is determined in relation to the most immediate parent element that has a position value of absolute, relative, or fixed. In the following example, the relative red square has a width set to 40% of the available space.
Horizontal and vertical position absolute middle.
.center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50% , -50%);
-webkit-transform: translate(-50%, -50%);
}
<div class="obj">
<div class="center">Test</div>
</div>
if you add display:table
to your #absolute
div you should get what you want:
http://jsfiddle.net/3KTUM/2/
This can be done with flexbox too:
#absolute {
align-items: center;
display: flex;
justify-content: center;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With