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
Margins of floated boxes do not collapse with margins of adjacent boxes. The root element ( <html> ) cannot be floated. An inline element that is floated is converted to a block-level element.
Answer 50faea7446ce3ec6a60004cf You cannot see the effect of margin-right because the 'width' property of div causes the margin of div to have more than 10px distance from the right wall of the body. Consequently, it causes the margin-right property not to have any visual effect.
margin: 10px 5px 15px 20px; top margin is 10px. right margin is 5px. bottom margin is 15px. left margin is 20px.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With