Bug or Feature? Weird CSS behavior with percentage margins

Welcome to my very first English post – please excuse all missspelling (latest German orthography tells us to use three letters if possible, e.g. “Schifffahrt” or “Schlussstrich”).
I discovered a very strange CSS behavior and could not find any advice, so I have to ask you and hope four your help. For that purpose, I created a new fiddle:


We have a div.container with 200px width and height. We have some inner divs with width, height, margin-bottom and margin-left of 20% ( =40px).
Well, what would you expect, if you change the width and height of the div.container? I expected, that width, height and margins of the inner div changes. They do but it’s a bit weird:

  1. Increasing the width of div.container increases the width of an inner div – expected!
  2. Increasing the height of div.container increases the height of an inner div – expected!
  3. Increasing the width of div.container increases the margin-left of an inner div – expected!
  4. Increasing the height of div.container does not increase the margin-bottom of an inner div, but increasing the width of div.container does – damn unexpected!

You can try it in the fiddle yourself. This happens with current Chrome, Firefox and Opera (Windows 7).

Can you explain this? Is there any reason (reference?) or is that really a bug?

I’m very appreciative!

Patrick

2 Kommentare

  1. Hi Eric, thank you for pointing out the papers.

    It’s really documented,even as an outstanding comment: „Note that in a horizontal flow, percentages on ‘margin-top’ and ‘margin-bottom’ are relative to the width of the containing block, not the height (and in vertical flow, ‘margin-left’ and ‘margin-right’ are relative to the height, not the width).“

    Well, this really sucks in my opinion. But with the tip from Eric in mind, I searched a bit deeper and there is a good reason for doing it this way:


    Element height is defined by the height of the children. If an element has padding-top: 10% (relative to parent height), that is going to affect the height of the parent. Since the height of the child is dependent on the height of the parent, and the height of the parent is dependent on the height of the child, we’ll either have inaccurate height, or an infinite loop. Sure, this only affects the case where offset parent === parent, but still. It’s an odd case that is difficult to resolve.

    via Ryan Kinal

Schreibe einen Kommentar zu Patrick Antworten abbrechen

Pflichtfelder sind mit * markiert.