Sub topic 3
Margin Collapsing and Related Box Behavior
This chapter assumes you know basic HTML, CSS selectors, and units such as px, em, rem, and %. It also assumes you understand content, padding, borders, and margins.
Margin collapsing
Vertical margins between normal block boxes can collapse into one margin. The gap uses the larger value, not the sum.
<style>
h2 { margin-bottom: 24px; }
p { margin-top: 16px; }
</style>
<h2>Heading</h2>
<p>Paragraph</p>The gap is 24px. Adjacent margins can also collapse between a parent and its first or last child when no border, padding, inline content, or separate formatting context prevents it.
Margins do not collapse between flex or grid items. A border or padding can also separate the margins.
Constraining size with min and max dimensions
Use min-width, max-width, min-height, and max-height to set limits. These properties are useful when content or the viewport can vary.
.article {
width: 100%;
max-width: 40rem;
min-height: 12rem;
}The element can become narrower than 40rem, but it cannot become wider. Its content area must also satisfy the minimum height.
Overflow
Overflow occurs when content does not fit inside its box. The overflow property controls the result.
.panel {
max-height: 12rem;
overflow: auto;
}auto adds scrolling only when needed. Other values include visible, hidden, and scroll. Fixed heights can cause clipped or hard-to-use content, so prefer flexible sizing when possible.
Block formatting contexts and `flow-root`
A block formatting context (BFC) is an independent layout region. It prevents certain margin interactions and contains floated descendants.
.card {
display: flow-root;
}This commonly prevents a first child's top margin from collapsing through the card and helps the card contain a floated child. Flex and grid containers also establish a separate formatting context.
Outline and box-shadow
An outline is drawn outside the border and does not take up layout space. A box shadow is also painted outside the box and normally does not change its size. Both can overlap nearby content.
Logical properties
Logical properties follow writing direction rather than physical sides:
.article {
max-inline-size: 40rem;
margin-inline: auto;
padding-block: 1rem;
}inline means the text direction, and block means the perpendicular direction. These properties work better for right-to-left and vertical writing modes.
Exercise
Two block elements have margin-bottom: 30px and margin-top: 20px. What is the gap in normal flow?
Show answer
The margins collapse, so the gap is 30px. The larger adjoining margin wins.