Reputation: 551
I used to align text inside DIVs with CSS and vertical-align
. I'm now trying, but I can't get it to work.
My task is to simply vertical-align: center;
the white text inside the pink DIV. But whatever I do, the text remains starting in the upper left corner.
Here is the HTML:
<div style="width:100%; text-align:center; background-color:#FF0000">
<div style="width: 587px; height: 180px; margin-left:auto; margin-right:auto; text-align:center; background-color:#00FF00">
<div style="height: 20px; width: 1px;"> </div>
<!--<br>-->
<div style="height: 30px; width: 530px; color: #FFFFFF; font-size: 16px; text-align: left; vertical-align: middle; margin-left:auto; margin-right:auto; background-color:#FF00FF">
<div style="display: table-cell; vertical-align: text-bottom;"> <b>Center me vertically, please!</b> </div>
</div>
</div>
</div>
You can also fiddle around with it.
I tried different solutions as found here on this site, but I can't get them to work. So why won't a browser vertically align my text in a nice pink DIV?
Upvotes: 0
Views: 59
Reputation: 1715
Add display: table
to the wrapping div and set vertical-align: middle
.
<div style="width:100%; text-align:center; background-color:#FF0000">
<div style="width: 587px; height: 180px; margin-left:auto; margin-right:auto; text-align:center; background-color:#00FF00">
<div style="height: 20px; width: 1px;"> </div>
<!--<br>-->
<div style="height: 30px; width: 530px; color: #FFFFFF; font-size: 16px; text-align: left; vertical-align: middle; margin-left:auto; margin-right:auto; background-color:#FF00FF; display: table;">
<div style="display: table-cell; vertical-align: middle;"> <b>Center me vertically, please!</b> </div>
</div>
</div>
</div>
JSfiddle: http://jsfiddle.net/gaecshs7/
Upvotes: 1
Reputation: 33071
I'm not sure if it's the "proper" CSS way to do it, but if you set the line-height
of your pink div to the same height (30px) then it will center vertically:
<div style="width:100%; text-align:center; background-color:#FF0000">
<div style="width: 587px; height: 180px; margin-left:auto; margin-right:auto; text-align:center; background-color:#00FF00">
<div style="height: 20px; width: 1px;">
</div>
<!--<br>-->
<div style="height: 30px; line-height: 30px; width: 530px; color: #FFFFFF; font-size: 16px; text-align: left; vertical-align: middle; margin-left:auto; margin-right:auto; background-color:#FF00FF">
<div style="display: table-cell; vertical-align: text-bottom;">
<b>Center me vertically, please!</b>
</div>
</div>
</div>
</div>
Upvotes: 2