hasLayout.net

Float Squeeze Weird Gap Bug

Affected Versions

This bug affects: IE7

Symptoms

A gap appears between last and second last floated elements that are stacked vertically.

Date of the Tutorial

Tue Aug 18 12:27:50 2009

Description

I am certain that this bug is caused by the same issue as the "Float Squeeze Duplicate Last Character Bug" as the setup is the same and the only difference is the number of floated elements (has to be more than three). The reason I created a separate tutorial for this bug is because it manifests itself differently as well as the solution is different. Let's look at the demo:

Demo

The demo is available on a separate page

HTML Code:
<div>
    <p>
        <span>A</span>
        <span>B</span>
        <span>C</span>
        <span>D</span>
    </p>
</div>
CSS Code:
div {
    width: 100px;
}
p {
    margin-right: 1px;
}
span {
    border: 1px solid #000;
    float: left;
    width: 120px;
}

The setup is as follows: we have an element - ' element"><div> in our demo - that has certain width set. Inside that element we have another one - ' element"><p> - with margin-right set to anything but zero . Inside that ' element"><p> we have four or more elements with float property set to value left and width set to a larger value than we have set on our ' element"><div>. What happens in affected browsers? A weird gap appears between the last and second last floated elements (in our demo that would be "C" and "D" ' element"><span>s).

Solutions

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

Solution (Clean Solution)

Date of the Solution

Tue Aug 18 12:28:06 2009

Fixed Versions

All of the affected

Description

Fixed demo is available on a separate page

HTML Code:
<div>
    <p>
        <span>A</span>
        <span>B</span>
        <span>C</span>
        <span>D</span>
    </p>
</div>
CSS Code:
div {
    width: 100px;
}
p {
    margin: 0 1px 0 0;
    width: 125px;
}
span {
    border: 1px solid #000;
    float: left;
    width: 120px;
}

What I did here is added width to our ' element"><p> (the container of floats) with the value that is larger than that of the floats. The width needed to contain the bug needs to be a "magic number" larger than the overal width of floated elements (that is their width plus padding and border if any of those are set). This magic number seems to be 3px. We have 120px width floats and 1px surrounding border set on them; this gives us 122px, add the magic number and we get 125px - solves the bug in both, although in IE7 the fix may be not related to the value of width but is fixed by "layout" that width gives.