I have a div thats about 200px x 40px. Sometimes this block will contain a single line of text and other times it will contain two lines. In the case that it contains 2 lines of text, I have adjusted the line height so that it looks balanced inside of the div. However, in the case that there is a single line of text, the text lines up with the top of the div, leaving the bottom empty.
Instead, I want the single line of text to appear vertically centered inside of the div. What is the best way to set this up? Should I place the text inside of a secondary element like <p>
and then attempt apply vertical-align: middle
? It seems like there should be a simpler, more streamlined way to accomplish this. Any Ideas?
I'm not sure if it works in any browser (works on Firefox, Chrome, IE8) (doesn't work on IE7-)
<div style="display: table-row; height: 180px; width: 500px;">
<div style="display: table-cell; vertical-align: middle; width: 500px; text-align: center;">Text</div>
</div>
The only solution I know that definitely works in any browser is to create a table and apply the vertical align on a cell.
Although it seems to be a simple problem there is no straightforward solution for it in CSS2 AFAK. Theme Forrest features a good overview of different approaches to this problem.
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