Seong Lee Seong Lee - 2 months ago 6
CSS Question

Margin not working with float elements

On my web page, I have a logo and a menu that make up header elements and a hero unit under it.
Now I want to give it some bottom margin so there is enough negative space between
header and hero unit but this bottom margin (100px) is not applying.
Same thing if I try to give top margin from hero unit.

.header {
width: 95%;
margin: 20px auto 100px;
}


Here is my working sample JS BIN

Answer

Adding a div under it with:

.someclass {
     clear: both;
}

would help. But even easier is:

.header {
    width: 95%;
    margin: 20px auto 100px;
    overflow: hidden;
}

If you add the overflow: hidden; the browser will be forced to calculate the size of the elements within, despite them being floated. When the size is calculated, it also knows where to start the margin-bottom.

One more popular uses of setting overflow, strangely enough, is float clearing. Setting overflow doesn't clear the float at the element, it self-clears. This means that the element with overflow applied (auto or hidden), will extend as large as it needs to encompass child elements inside that are floated (instead of collapsing), assuming that the height isn't declared.

Source

The difference between auto and hidden in this case, is that with hidden, it will hide everything that overflows, when it doesn't have enough room anymore, and with auto, it will create a scrollbar.

EDIT:

Since this question apparently is still active, I'll add the most common way of solving this in the present day:

.header:after {
    clear: both;
    height: 0;
    width: 100%;
    content: '';
    display: block;
}

This is the same as the first method, but then without having to add another element. This is the way to go if setting overflow is not an option (or even if it is an option, this would be better).

When I first posted this answer, it wasn't an option as it was not supported by IE 6 / 7, which were still broadly used back then.