Pro HTML5 and CSS3 Design Patterns

(avery) #1
CHAPTER 13 ■ BLOCKS

Collapsed Margins


Problem You want to collapse or uncollapse vertical margins between blocks.^


Solution Browsers collapse vertical margins into the larger of the bottom and top margins between
sibling blocks. For example, if the bottom margin of one block is 15 pixels and the top
margin of the next sibling block is 10 pixels, the collapsed margin is 15 pixels (the
uncollapsed margin is 25 pixels).
You can literally prevent the collapsing of the first child’s top margin into its parent’s top
margin by assigning a top padding or a top border to the parent. Likewise, you can prevent
the collapsing of the last child’s bottom margin into its parent’s bottom margin by assigning
bottom padding or a bottom border to the parent. You can hide the padding or border by
making it transparent and as small as one pixel. In the example, the vertical margins of the
second paragraph do not collapse into its parent because its parent has top and bottom
borders.
You cannot prevent vertical margins from collapsing between sibling blocks. If you want to
avoid the collapsing effect between siblings, you can set margins to zero and use
transparent borders or transparent padding instead. Borders and padding do not collapse.
When a parent block does not have a border, the top margin of its first child collapses into
its top margin. Likewise, the bottom margin of the last child collapses into the parent’s
bottom margin.


Patterns Uncollapsed Margins Between Parent and Child Blocks


PARENT_SELECTOR { border-top: WIDTH STYLE COLOR;
border-bottom: WIDTH STYLE COLOR;
padding-top:+VALUE; padding-bottom:+VALUE; }

Uncollapsed Margins Between Sibling Blocks

SIBLING_SELECTOR { padding-top:+VALUE; margin-top:0;
padding-bottom:+VALUE; margin-bottom:0;
background-color:transparent; }
or
SIBLING_SELECTOR { margin-top:0; margin-bottom:0;
border-top:+VALUE solid transparent;
border-bottom:+VALUE solid transparent;
background-color:transparent; }

Location This pattern applies to block elements and elements displayed as blocks.


Disadvantage Using padding or borders to prevent collapsing margins prevents you from using padding
and borders for what they were intended.


Related to Horizontal Rule, Block Spacer, Block Space Remover; Margin, Border, Padding (Chapter 6);
Spacing, Blocked (Chapter 11), Collapsed Borders (Chapter 15)

Free download pdf