Development Tip: Center Text Vertically using line-height
A very common beginner’s problem for coders is centering text vertically within a DIV.
Lets say you have this HTML & CSS for a button:
<style type="text/css">
.button {
background-color:#222;
color:#fff;
height:25px;
text-align:center;
vertical-align:middle;
width:85px;
}
</style>
<div class="button">Submit</div>
You’d think that vertical-align would center the text vertically, but it does not work in a DIV. The typical fix for this is to add padding to the top and/or bottom of the div and hope it looks good in every browser. While this is a legit fix – and a good one if you do not have a fixed height – there is an even better one for divs that only have one line of text and a fixed height: using a line-height that equals the height of the div.
Your CSS should look like this – the important parts are in red:
<style type="text/css">
.button {
background-color:#222;
color:#fff;
height:25px;
line-height:25px;
text-align:center;
width:85px;
}
</style>
In the end, your div will look like this:
A nice clean, hack-free fix.