hasLayout.net

No line-height Vertical Center on Images Bug

Affected Versions

This bug affects: IE7

Symptoms

Images are not vertically centered using line-height method

Date of the Tutorial

Sat Jul 18 11:39:56 2009

Description

Here's a bug that sure has killed some of my brain cells back in the day. I often make "product pages" with lots of different-sized thumbs that I like to put in even sized boxes to make them look pretty... even since the time I found a fix for this bug, I still hate it quite a bit because the only solution I can find requires adding extra markup. Anyway, let's take a gander at the demo:

Demo

HTML Code:
<div><img src="hl_logo.png" alt="" width="95" height="115"></div>
<!-- NOTE: no white-space in the <div> also triggers bug in IE7 -->
CSS Code:
div {
    width: 150px;
    height: 155px;
    line-height: 155px;
    text-align: center;
}
img {
    vertical-align: middle;
}

In IEs below IE8 the image of a ladybug is not vertically centered (hey, at least it's displayed at all!).

Solutions

Below are solutions for the above bug ordered by the solution type.

Solution (Clean Markup Solution)

Date of the Solution

Sat Jul 18 11:52:58 2009

Fixed Versions

all of the affected

Description

Now, I would say that while this solution is marked as "Clean Markup Solution", if the lowest IE version that you are supporting is 7, then simply add the whitespace inside the div (that is, the ' element"><span> element is needed only for IE below 7)

HTML Code:
<div>
    <img src="hl_logo.png" alt="" width="95" height="115">
    <span></span>
</div>
<!-- NOTE: <span> is not needed for IE7; whitespace is enough -->
CSS Code:
div {
    width: 150px;
    height: 155px;
    line-height: 155px;
    border: 1px solid #000;
    background: #f00;
    text-align: center;
}
img {
    vertical-align: middle;
}
span {
    display: inline-block;
}

Note that we added an extra span for fixing the bug in IE versions below 7; we also used display property set to inline-block to give our precious span "layout". End result - everything works fine.