Reputation: 253
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;
}
Upvotes: 25
Views: 40207
Reputation: 261
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>
Upvotes: 22
Reputation: 256
This can be done with flexbox too:
#absolute {
align-items: center;
display: flex;
justify-content: center;
}
Upvotes: 12
Reputation: 50563
Just make the div relative
to its absolute
parent and use text-align: center
, like this:
.centerd {
position: relative;
width: 100%;
text-align: center;
/*display:table-cell;
vertical-align:middle;*/
}
See example fiddle
Upvotes: 2
Reputation: 128791
Change your #absolute
div to also use:
display:table;
vertical-align:middle;
text-align:center;
Upvotes: 7
Reputation: 58432
if you add display:table
to your #absolute
div you should get what you want:
Upvotes: 14