I know how to vertically align a text center within a div when the height of text is known. Say the text's height is 20px.
Wrap the text with a span. Style div & span.
div {
position: relative;
}
span {
display: block
position: absolute;
top: 50%;
height: 20px;
margin-top: -10px;
}
Now I want to responsively align the text. What I want is the font-size of the text be in proportion to the height of the body. Say I have the following style:
body {
font-size: 100%;
}
span {
font-size: 1.5em;
}
Then I will change the font-size of body when the window size changed. In this situation, the height of the text is not determined. Then how to vertically align the text middle?
I know I can use JavaScript to dynamically change the height and margin-top of the span. But I have to do this after the window size changed. Then there is a chance that the window size changed, then the user see the the text not in the middle, then the JS code executed and the text jumped to the middle of the div. This may not be an acceptable solution.
I want to know if there is a pure CSS solution.
I guess I can use the following style to vertically align the text center.
div {
display: table-cell;
vertical-align: middle;
}
But with this solution, the margin of the div is not rendered properly. And the semantic is not right.
So is there a perfect solution?