Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS layout breaks without border on div

Tags:

css

I've came across with this issue several times. Still have no clue what causes this.

Reproduce:

  1. Open http://jsbin.com/ibowed/1/edit
  2. In CSS panel find .l-search-index .top { @ line 26
  3. change border: 1px solid #ff0000; to border: 0;
  4. whaaat?

Browser: chrome, but I think u can try in any other..

Please advise!

like image 423
zsitro Avatar asked May 08 '13 11:05

zsitro


1 Answers

It's to do with the way margins overlap, and how certain properties force them to be contained. If you place 2x divs on a page, both with margins 100px, the spacing between those divs will be 100px. Not 200px. That's because the margins are allowed to overlap other margins. That's just how margins work. It's a good thing.

But if you put a div inside another div, both with margins, then the those margins also overlap. The child element's margins overlap the parent's.

But, some properties — border, as you've discovered, but also padding and overflow — force the parent to contain the margins of its child instead of overlapping them.

I'm sure someone can give a more technical explanation, but that's how I think about what's happening.

Here is a simplified test case: http://jsbin.com/ukodus/2/
Remove the // before any of the lines of CSS to see the effect.


"This behavior is called margin collapse. Only top/bottom margins will collapse, not left/right." — @cimmanon

like image 152
Dominic Avatar answered Oct 10 '22 20:10

Dominic