How can I vertically center some simple text in a normal <div>
? I have markup like this:
<div style="height:200px;">
<span style="display:inline; vertical-align:middle;">ABOUT</span>
<div>
It doesn't work under either Firefox or Internet Explorer. Why not?
For vertical alignment, set the parent element's width / height to 100% and add display: table . Then for the child element, change the display to table-cell and add vertical-align: middle . For horizontal centering, you could either add text-align: center to center the text and any other inline children elements.
To center an element both vertically and horizontally: position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; But if you would like to understand how I came to these solutions, read further for more explanation.
1 Select the text you want to center between the top and bottom margins. 2 On the Page Layout tab, click the Page Setup Dialog Box Launcher. 3 Select the Layout tab. 4 In the Vertical alignment box, click Center 5 In the Apply to box, click Selected text, and then click OK.
That's not what vertical-align
does. You probably want line-height
:
<div>
<span style="line-height: 200px;">ABOUT</span>
</div>
Here's a demo.
I have found using a spacing element to the most reliable method of centering any element you know the height of (image, text). This will center an element in a container of any height.
CSS:
#outer {
background: grey;
height: 200px; /* any height */
}
#outer > div {
height: 50%;
margin-bottom: -6px;
}
#outer span {
font-size: 12px;
}
HTML:
<div id="outer">
<div></div>
<span>Example</span>
</div>
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