I have a <div>
that is containing a sentence. The height of <div>
is based of %
(its height is changeable - depends on size of screen). Now I want to keep that sentence in the center (vertically) of <div>
, How can I do that?
Here is a sample of what I said:
div{
position:absolute;
border: 1px solid;
width: 250px;
height: 60%;
text-align: center;
}
<div>This should be center vertically</div>
My favorite technique is to add an ::after
pseudo-element to the parent element, wrap all the element's children in a single element, and let that element and the ::after
pseudo-element play the inline-block, vertical-alignment game:
div{
position:absolute;
border: 1px solid;
width: 250px;
height: 60%;
text-align: center;
}
div span {
display: inline-block;
vertical-align: middle;
}
div::after {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
}
<div><span>This should be centered vertically, and now it is!</span></div>
The ::after
pseudo-element having height: 100%
will expand dynamically with the height of the parent, thus the inner element will always be centered vertically.