In a document tree, each element generates zero or more principal boxes. The layout of that boxes is governed by:
1. Box dimensions
The perimeter of each of the four areas (content, padding, border, and margin) is called an “edge”, each box has four edges:
- content edge or inner edge: The content edge surrounds the rectangle given by the width and height of the box, which often depend on the element’s rendered content. The four content edges define the box’s content box.
- padding edge: The padding edge surrounds the box padding. If the padding has 0 width, the padding edge is the same as the content edge. The four padding edges define the box’s padding box.
- border edge: The border edge surrounds the box’s border. If the border has 0 width, the border edge is the same as the padding edge. The four border edges define the box’s border box.
- margin edge or outer edge: The margin edge surrounds the box margin. If the margin has 0 width, the margin edge is the same as the border edge. The four margin edges define the box’s margin box.
In other words:
- content area is the area formed by the content edge.
- padding area is the area formed by the content edge and padding edge.
- border area is the area formed by the padding edge and the border edge.
- margin area is the area formed by the border edge and the margin edge.
Margin properties specify the width of the margin area. The
margin shorthand property sets the margin for all four sides.
Vertical margins have no effect on non-replaced inline-level elements:
Percentage margins are calculated with respect to the width of the containing block:
Check out Computing widths and margins for more info.
2.2. Collapsing vertical margins
Two adjoining vertical margins collapse if:
- both belong to in-flow block-level boxes that participate in a same block formatting context.
- no line boxes, no clearance, no padding and no border separate them.
- both belong to vertically-adjacent box edges, i.e. form one of the following pairs:
- top margin of a box and top margin of its first in-flow child.
- bottom margin of box and top margin of its next in-flow following sibling.
- bottom margin of a last in-flow child and bottom margin of its parent if the parent has
- top and bottom margins of a box that does not establish a new block formatting context and that has zero computed
min-height, zero or
height, and no in-flow children.
Non-percentage paddings are straightforward and easy to calculate:
As you can see, both top and right have 32px (2 x 16px) of computed padding.
Percentage paddings are calculated with respect to the width of the containing block, even for vertical paddings. For example:
If we don’t declare a width for a block-level box, and the box has static or relative position, the padding push inwards instead of outward: