zsitro
zsitro

Reputation: 1892

CSS layout breaks without border on div

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!

Upvotes: 7

Views: 1987

Answers (3)

Dominic
Dominic

Reputation: 2447

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

Upvotes: 7

Christoph
Christoph

Reputation: 51201

This is a quite unintuitive case of collapsing margins:

§ 8.3.1 of the CSS Spec explains how margins are handled and under which circumstances they collapse. The rules are not too easy to understand (has several special cases), but I quote the relevant parts of the spec for you:

In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin.

Two margins are adjoining if and only if: no line boxes, no clearance, no padding and no border separate them

(emphasized by me)

So, as soon as you remove the border, the vertical margins of your elements collapse. Your case makes it a bit complicated since you have negative margins.

To fix this you could set the overflow property or apply a padding:1px on the .top element.

Upvotes: 6

Nitesh
Nitesh

Reputation: 15759

Here is the solution.

.l-search-index .top{border: 0; height: 70%; overflow: auto;}

You have to add an overflow.

Hope this helps.

Upvotes: 1

Related Questions