The Box Model, Display, and Positioning: Why Your Layout Breaks (And How to Fix It)

The CSS box model explained: box-sizing, margin collapse, display types, formatting contexts, containing blocks, and a fix for each layout bug.

Executive Summary: Most broken layouts come from five mechanisms: how box sizes are added up (box-sizing), vertical margins collapsing, the outer and inner display type of each box, which ancestor acts as the containing block for positioned elements, and which ancestor creates a stacking context for z-index. Learn to name the mechanism behind a symptom and the fix is usually one line.
Nested diagram of the CSS box model with margin, border, padding and content layers

A sidebar is set to width: 300px. Someone adds padding: 20px and a 1px border, and the sidebar drops below the main column. Elsewhere, a modal with position: fixed suddenly scrolls with the page. A dropdown with z-index: 9999 renders under a card with z-index: 1. Three bugs, three different mechanisms, and none of them is a browser quirk.

The CSS box model describes every element as a rectangle made of content, padding, border and margin. Display decides how that box takes part in layout and how it lays out its children. Positioning decides whether the box stays in normal flow or is placed relative to something else. Together they are the foundation under Flexbox and Grid, and most “Flexbox bugs” turn out to be box model bugs.

My position: you should be able to explain every layout bug in terms of one of five mechanisms before you touch the CSS. Guess-and-check with position: relative and bigger z-index values is how stylesheets rot.

The box model and box-sizing

Every box has four layers, from the inside out: the content area, padding, border and margin. Background paints under content, padding and border. Margin is always transparent and sits outside the border.

+---------------- margin ----------------+
|  +------------- border -------------+  |
|  |  +---------- padding ---------+  |  |
|  |  |                           |  |  |
|  |  |          content          |  |  |
|  |  |                           |  |  |
|  |  +---------------------------+  |  |
|  +---------------------------------+  |
+---------------------------------------+

The default, box-sizing: content-box, applies width and height to the content area only. Padding and border are added on top. So the sidebar from the opening example is 300 + 20 + 20 + 1 + 1 = 342px wide, and it no longer fits.

With box-sizing: border-box, width includes padding and border. The sidebar stays 300px and the content area shrinks to 258px. That matches how designers think about sizes, which is why nearly every reset sets it globally:

html {
  box-sizing: border-box;
}

*,
*::before,
*::after {
  box-sizing: inherit;
}

Using inherit instead of setting border-box on * directly means a third-party widget that needs content-box can set it once on its root, and its descendants follow.

Margin collapse: the bug that is actually a feature

In normal block flow, vertical margins between boxes can merge into one. This is called margin collapsing, and it happens in three situations:

  • Adjacent siblings: a margin-bottom: 24px followed by a margin-top: 16px produces a 24px gap, not 40px. The larger margin wins.
  • Parent and first or last child: if a parent has no border, padding or inline content separating it from its first child, the child’s top margin escapes through the parent. A heading’s margin-top pushes the whole card down instead of creating space inside it.
  • Empty blocks: an element with no height, padding or border collapses its own top and bottom margins together.

It exists for text. Paragraphs with margin: 1em 0 get one em between them, not two, without any extra rules. The bug appears when you build components with margins and the space ends up outside the component.

Margins never collapse in these cases, which gives you the fixes:

  • Children of flex and grid containers. Margins between flex or grid items always add up.
  • Across a border or padding on the parent.
  • Across a new block formatting context, which display: flow-root creates cleanly.
  • Horizontal margins. Only block-direction margins collapse.

The modern habit is to space siblings with gap on a flex or grid parent rather than margins on children. Gap never collapses, never leaks out of the parent, and never leaves a stray margin on the last item.

Display: outer type and inner type

The display property sets two things at once. The outer display type decides how the box behaves among its siblings: block boxes start on a new line and fill the available width, inline boxes flow within a line of text. The inner display type decides how the box lays out its own children: normal flow, flex, grid and so on.

The single keywords you know are shorthands for pairs. Since 2023 every major browser also accepts the two-keyword form, which makes the pairing explicit:

Single keyword Two-keyword form Outer behavior Children laid out as
block block flow New line, full width Normal flow
inline inline flow Inside a line of text Normal flow
inline-block inline flow-root Inside a line, but sized like a block Normal flow, new formatting context
flow-root block flow-root New line, full width Normal flow, new formatting context
flex block flex New line, full width Flex items
inline-flex inline flex Inside a line Flex items
grid block grid New line, full width Grid items

Two values sit outside this model. display: none removes the box and its descendants from layout and from the accessibility tree. display: contents removes the element’s own box but keeps its children, which then act as children of the grandparent. It is handy for letting list items join a parent grid. Test it with a screen reader before shipping, because browsers have a history of dropping semantics, such as a list’s role, from elements with display: contents.

Why inline elements ignore your width

Inline boxes such as span, a and strong do not accept width or height, and their vertical margins do not push other lines away. Vertical padding paints but does not affect line height, so a padded link overlaps the lines above and below. If you need a sized box that still sits inside text, use inline-block or inline flex.

The same model explains the mysterious gap under images. An img is inline by default, so it sits on the text baseline and leaves room below for letter descenders like “g” and “y”. Set display: block on images that stand alone, or vertical-align: middle on ones that sit in text.

Formatting contexts

A block formatting context (BFC) is an isolated region of layout. Floats inside it stay inside it, outside floats do not overlap it, and margins do not collapse across its edge. Many properties create one as a side effect: floats, absolute positioning, overflow other than visible or clip, inline-block, flex and grid items, and contain: layout or paint.

The side effects are where old hacks came from. overflow: hidden on a parent “fixed” collapsing floats because it created a BFC, while also clipping any dropdown that tried to escape. Use the property built for the job:

.media {
  display: flow-root;   /* contains floats, stops margin collapse, clips nothing */
}

Flex and grid containers create their own formatting contexts for their children, which is why margins inside them never collapse.

Positioning and the containing block

The position property has five values. The first question for any positioned element is: relative to what? The answer is its containing block, and that is where most positioning bugs live.

Value In normal flow? Offsets relative to Common use
static Yes Offsets are ignored The default
relative Yes, space is kept Its own normal position Nudging, and acting as a containing block
absolute No Nearest positioned ancestor’s padding box Badges, overlays, icons in inputs
fixed No The viewport, with exceptions below Headers, modals, toasts
sticky Yes, until a threshold Its nearest scrolling ancestor Table headers, section titles

For position: absolute, the containing block is the nearest ancestor whose position is anything other than static. If none exists, it is the initial containing block, roughly the first screen of the page. That is why a badge with top: 0; right: 0 flies to the corner of the page: its card was never given position: relative.

Use the inset shorthand to set all four offsets at once. inset: 0 stretches an absolutely positioned overlay to fill its containing block.

.card {
  position: relative;          /* becomes the containing block */
}

.card__badge {
  position: absolute;
  inset-block-start: 0.5rem;   /* top in horizontal writing modes */
  inset-inline-end: 0.5rem;    /* right in left-to-right languages */
}

Why your fixed modal scrolls with the page

The spec has a rule that surprises everyone once. If any ancestor has a transform, filter, perspective, backdrop-filter, contain: layout or paint, or will-change set to one of those, that ancestor becomes the containing block for position: fixed descendants. The modal is now fixed to the transformed element, not the viewport.

This bites when a page-transition animation applies transform to the page wrapper, or a card hover effect uses transform: translateY(-2px) and a tooltip inside it is fixed. Two fixes work. Render overlays outside transformed ancestors, usually at the end of body. Or use the browser’s top layer through <dialog> with showModal() or the popover attribute. Top-layer elements escape every ancestor’s containing block, clipping and stacking context. The anchor positioning guide builds tooltips this way.

Why position: sticky does nothing

Sticky positioning fails silently in three ways:

  1. No threshold. Without top, bottom, left or right, there is nothing to stick to.
  2. An ancestor scrolls or clips. A sticky element sticks within its nearest scrolling ancestor. Any ancestor with overflow: hidden, auto or scroll becomes that scroller, even if it never actually scrolls. If you only needed clipping, overflow: clip clips without creating a scroll container.
  3. No room to move. The element sticks only within its parent’s box. If the parent is exactly as tall as the sticky element, it has nowhere to go. In a flex or grid row, the default align-items: stretch causes exactly this; set align-self: start on the sticky child.

Stacking contexts and z-index

z-index works on positioned elements and on flex and grid items. It does not compare values across the whole page. It compares them only among siblings inside the same stacking context. An element with z-index: 9999 inside a stacking context that sits at z-index: 1 can never rise above a sibling context at z-index: 2.

New stacking contexts come from more places than people expect:

  • A positioned element with any z-index other than auto.
  • position: fixed or sticky, even without z-index.
  • A flex or grid item with a z-index.
  • opacity below 1, transform, filter, backdrop-filter, mix-blend-mode other than normal, clip-path, mask.
  • isolation: isolate, contain: layout or paint, and will-change naming any of the above.

The constructive use is isolation: isolate. Put it on each component root and the component’s internal z-index values (1, 2, 3) stay internal. They cannot leak out and fight other components, so you never need a global z-index scale beyond a handful of layers: content, sticky header, overlays.

.card {
  isolation: isolate;     /* internal z-index stays internal */
}
.card__image   { z-index: 0; position: relative; }
.card__overlay { z-index: 1; position: absolute; inset: 0; }

A symptom-to-cause lookup table

Symptom Mechanism Fix
Element wider than its width Content-box sizing box-sizing: border-box
Gap between siblings smaller than expected Margin collapse Use gap on a flex or grid parent
Child margin pushes the parent down Parent-child margin collapse display: flow-root or padding on the parent
Width ignored on a link or span Inline outer display inline-block or inline flex
Thin gap under an image Baseline alignment display: block on the image
Absolute element jumps to page corner No positioned ancestor position: relative on the intended parent
Fixed element scrolls with content Transformed ancestor Move it out, or use dialog or popover
Sticky does nothing Overflow ancestor or no room overflow: clip, align-self: start
High z-index still underneath Trapped in a stacking context Fix the context; use isolation: isolate
Dropdown clipped by its card overflow: hidden on an ancestor Top layer via popover

Frequently Asked Questions

What is the difference between content-box and border-box?

With content-box, width and height set the content area, and padding and border are added on top. With border-box, width and height include padding and border, so the element’s visible size matches the number you wrote. Most projects set border-box globally.

Why is my z-index not working?

Either the element is not positioned and is not a flex or grid item, so z-index does not apply, or it sits inside a stacking context created by an ancestor with opacity, transform, filter, or its own z-index. z-index only competes with siblings in the same stacking context.

Why is position sticky not working?

The usual causes are a missing top or bottom value, an ancestor with overflow set to hidden, auto or scroll, or a parent that is no taller than the sticky element. In flex and grid rows, set align-self: start so the sticky item has room to move.

Why does position fixed not stay fixed to the viewport?

An ancestor with transform, filter, perspective, backdrop-filter or certain contain values becomes the containing block for fixed descendants. Move the element outside that ancestor or render it in the top layer with dialog or popover.

Name the mechanism first

Layout bugs feel random until you sort them into these five buckets: sizing, margin collapse, display type, containing block and stacking context. Once you name the bucket, the fix is usually one property, and the stylesheet stays clean. With this foundation in place, the Flexbox mental model and CSS Grid become much easier, because they reuse every rule here.

Rule of thumb: before changing a value, say out loud which of the five mechanisms caused the bug.

Originally posted on 25 March 2025 and post last modified on 25 March 2025

Box Model CSS CSS Layout CSS Positioning Front-End Development

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *