tags:

views:

160

answers:

2

I've got a website which has a layout sorta like this:

<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en">
  <body style="margin:0px">
    <div style="border-left: 5px solid black;">
      <div><!-- x -->
        <div>
          <div>
            <div style="margin-top: 100px">
              fish
            </div>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

I want the entire page to have a border down the left side. However, it seems the deeply-nested div's 100px top margin is causing its ancestor's border-left to get pushed down.

For some reason, if i uncomment the "x", everything looks great.

What is going on?!?!

+4  A: 

Margins collapse, even with contained elements, so your inner div's margin is pushing the outer div down. Fortunately, the solution is simple: add "overflow: auto" to your outer div's styles (the one with the border).

<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en">
  <body style="margin:0px">
    <div style="border-left: 5px solid black; overflow: auto;">
      <div><div><div>
        <div style="margin-top: 100px">fish</div>
      </div></div></div>
    </div>
  </body>
</html>
Ben Blank
Ah, there's the simple CSS fix I was thinking of! +1
William Brendel
+1  A: 

For some reason, if i uncomment the "x", everything looks great.

Yeah, with the ‘x’ in place there is some content in the way, between the child margin-top and the parent margin-top. Margins can't collapse through content, padding or borders, so another fix is to put any amount of top padding or border on any element between the marginned div and the bordered div. For example if the bordered element also has a top border, the left border will jump up to join it at the top.

Ben's answer is a common method using a side-effect to prevent margin collapsing, due to this line in section 8.3.1 of CSS2.1:

Vertical margins of elements with 'overflow' other than 'visible' do not collapse with their in-flow children.

But for clarity it might be better to avoid margin collapsing if you can. Using padding in preference to top and bottom margins where possible is generally a good tactic, as the margin-collapsing rules in CSS are unintuitive and unhelpful, and will bite you again and again — even ignoring the bugs in IE6's implementation.

bobince