How to use vertical-align in CSS
Posted 8 months, 2 weeks ago at 3:05 am. 0 comments
Poor vertical align still gets a bad rap. While it probably wouldn’t top the list of least used CSS properties (clip may have earned that title), it certainly should get an honorable mention as one of the most avoided and least understood.
I think this is because most coders would expect vertical-align to align an element vertically in its container. Instead it vertically aligns an element in relation to the line-height. For example, #div {vertical-align: middle; } would give us:

While #div {vertical-align: middle; line-height: 2em; } gives us:

To make matters worse, there are other scenarios that may not work as expected. For example:
CSS
#exampleContainer {
vertical-align: middle;
line-height: 2em;
width: 200px;
height: 2em;
border: 1px solid red;
}
HTML
<div id="exampleContainer">text<img src="http://vertical-align.com/image.jpg" width="2" height="25" /></div>
This gives us text that is vertically aligned in the middle in the first box, but it isn’t where we wanted it in the second.

If we add a vertical-align declaration specifically for the image then we get the intended result with the text.
#exampleContainer img {
vertical-align: middle;
}
