Why does 10px + 10px = 10px?
Asked Answered
L

3

8

I have the following script where the margin for the . portlet class is behaving strangely:

http://jsfiddle.net/mYx5y/19/

it should be adding 10px around each portlet, which should mean a gap of 20px between portlets. For some reason, I am only getting 20px if a portlet has a widget to the right or left of itself, but only 10px if the portlet has another portlet above or below it.

Why am I getting 10px vertically?

Lemcke answered 14/3, 2011 at 11:0 Comment(0)
R
11

Because margins don't add up, they collapse. If you have two elements A and B, A margin=10px and B margin=15px, the spacing between A and B will be 15px.

Two solutions:

  1. Use margin-bottom: 20px, margin-top: 0px
  2. Wrap them into a container and apply padding: 10px 0;
Rubadub answered 14/3, 2011 at 11:5 Comment(0)
Q
7

Because margins collapse, they are not added, just max()-ed (the biggest margin value of neighbouring objects will be used). Use padding if the space is part of your element.

Qua answered 14/3, 2011 at 11:4 Comment(5)
So margins only collapse vertically, and not horizontally?Lemcke
I'm pretty sure they do the same thing horizontally too. But you can use many techniques in your sitebuild to achieve a multiple column structure. If they are not collapsing horizontally the secet may lie in your other html tags, css.Qua
From w3.org/TR/CSS21/box.html#collapsing-margins - "In CSS 2.1, horizontal margins never collapse. "Battleplane
w3.org/TR/CSS21/box.html#collapsing-margins says, "In CSS 2.1, horizontal margins never collapse."Laurin
OK, you convinced me, they don't :) I tried to say that you rarely use normal flow when you creating a multicolumn sitebuild.Qua
B
5

This is how margins work. Adjacent vertical margins collapse into each other:

Two or more adjoining vertical margins of block-level boxes in the normal flow collapse. The resulting margin width is the maximum of the adjoining margin widths. In the case of negative margins, the maximum of the absolute values of the negative adjoining margins is deducted from the maximum of the positive adjoining margins. If there are no positive margins, the absolute maximum of the negative adjoining margins is deducted from zero. Note. Adjoining boxes may be generated by elements that are not related as siblings or ancestors.

See also: Collapsing margins

Battleplane answered 14/3, 2011 at 11:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.