I just learnt a new \"css hack\" from my teacher. But he don\'t know why it works.
I\'ll explain:
I\'ve on my website a gap (the green line) which I don\'t want
The browser always collapses the margins with the nearby margins. When you give an overflow: hidden
, it calculates all the contents inside it's box model and makes it confine to the content.
Explanation for BoltClock and anyone else. Sorry about my quick dirty handwriting...
This is the same case with float
s too. Floated items do not occupy any space. Have a look here:
div {padding: 5px; border: 1px solid #666;}
<div>
<div style="float: left;"></div>
</div>
But the same thing, if the parent has an overflow: hidden
it doesn't happen:
div {padding: 5px; border: 1px solid #666;}
<div style="overflow: hidden;">
<div style="float: left;"></div>
</div>
A whole big article about this concept here: What You Should Know About Collapsing Margins. The overflow
is such a powerful property that it works for everything. But when it comes to position
you need to use it carefully!
The position
works like float
, in the way that both do not take the layout. For eg., see the below snippet:
div {padding: 5px; border: 1px solid #666;}
<div>
<div style="position: absolute;"></div>
</div>
Where, if you play with it in the wrong way:
div {padding: 5px; border: 1px solid #666;}
<div style="overflow: hidden; position: relative;">
<div style="position: absolute;"></div>
</div>
The contents above get cut. Hope it is clear.
overflow: hidden
causes the container element to establish a block formatting context, which blocks parent-child margin collapse (though not other forms of margin collapse). This effect is mentioned explicitly in the section on collapsing margins:
- Margins of elements that establish new block formatting contexts (such as floats and elements with 'overflow' other than 'visible') do not collapse with their in-flow children.
As a result, the margins of the p
element do not bleed out of the content box of its parent.
You would delete, or zero out, the margins if you absolutely do not want any margins surrounding the p
element. Blocking margin collapse between the p
element and its parent does not remove the margins from either element.