Boxes, Flow, Display and Positioning
Predict an element’s size from the box model, read how blocks and inline boxes flow, and place elements deliberately with relative, absolute, fixed and sticky positioning.
Contentsand lesson path
On this page
- Why it matters
- The box model and box-sizing
- Normal flow and margin collapsing
- display: what kind of box is this?
- position: taking a box out of flow
- Check your understanding
- Apply it
- Review prompt
Lessons of CSS Cascade & Box Model
- Selectors and How Rules Find Elements Concept · 20 min
- Untangling the Cascade, Specificity and Layers Worked example · 25 min
- Boxes, Flow, Display and Positioning Concept · 25 min
- Units, Type, Color and Motion Concept · 25 min
- Lab: Debug a Broken Stylesheet in DevTools Lab · 25 min
- Check: Predict the Computed Style Knowledge check · 10 questions
What you will learn
- Size and space elements with the box model (content, padding, border, margin, box-sizing), normal flow and block vs inline display.
- Apply typography, color and relative units (rem, em, %, viewport units, ch) and place elements with relative, absolute, fixed and sticky positioning.
Prerequisites: Semantic HTML
01. Why it matters
The browser lays out a page by giving every element a rectangular box and stacking the boxes according to simple rules: normal flow for the default, and your overrides — display, sizing and positioning — on top. Almost every "why is there a gap here", "why did my width get ignored" and "why is this menu floating over the wrong corner" question reduces to one of those rules.
This lesson walks the four you need daily: the box model and its two sizing modes, how normal flow arranges blocks and inline boxes (including margin collapsing), what display switches between, and how position takes an element out of flow. Every number in the output blocks below was measured in Chromium at a 1280-pixel-wide window, and the test page, its stylesheet and the measurement snippets are all printed so you can reproduce them.
02. The box model and box-sizing
From the inside out, an element's box is its content, wrapped in padding, wrapped in border, wrapped in margin. Padding and border belong to the box; margin is space the box pushes between itself and its neighbours. box-sizing decides what the width property measures:
content-box(the default):widthsets the content only. The visible box adds padding and border on top, so it ends up wider than you asked.border-box:widthsets the border edge — padding and border are carved out of the width, so the visible box is exactly as wide as you asked.
Most stylesheets set border-box on everything (*, *::before, *::after { box-sizing: border-box; } is the usual reset line) precisely because arithmetic you can do in your head beats arithmetic that surprises you. See it measured:
.content-box {
box-sizing: content-box; /* the default */
width: 200px;
padding: 20px;
border: 5px solid teal;
}
.border-box {
box-sizing: border-box; /* carved out of the width */
width: 250px;
padding: 20px;
border: 5px solid teal;
}<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Boxes and flow</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="cb" class="content-box">content-box</div>
<div id="bb" class="border-box">border-box</div>
<p id="p1" class="first">First paragraph</p>
<p id="p2" class="second">Second paragraph</p>
<p id="line-inline">A <span id="chip1" class="chip">new</span> chip</p>
<p id="line-iib">A <span id="chip2" class="chip chip-inline-block">new</span> chip</p>
<div id="card" class="card">
Card text
<span id="badge" class="badge">Sale</span>
</div>
</body>
</html>Every snippet in this lesson runs in the DevTools console of this one page, and every CSS block in the lesson goes into the styles.css it links. Open index.html in a 1280-pixel-wide window, then paste each snippet as you reach it.
for (const id of ['cb', 'bb']) {
const w = document.getElementById(id)
.getBoundingClientRect().width;
console.log(id + ' outer width = ' + w + 'px');
}cb outer width = 250px (200 + 2 x 20 padding + 2 x 5 border)
bb outer width = 250px (exactly the width that was set)Different width values, same 250-pixel result — the models measure from different edges. In the DevTools Computed panel the box model diagram draws these layers to scale, which makes it the fastest place to answer "why is this element 250 pixels when I said 200?"
03. Normal flow and margin collapsing
With no styling at all, block-level boxes stack vertically, each taking the full available width; inline boxes flow along lines inside them. This is normal flow, and well-behaved documents need nothing more.
The classic surprise is margin collapsing: the bottom margin of one block and the top margin of the next do not add up — they collapse into a single margin the size of the larger. Neither wins; both exist, one space results. Margins only collapse vertically between blocks in normal flow, and they refuse to collapse inside flex and grid containers, which is one quiet reason those layouts feel more predictable.
.first { margin-bottom: 24px; }
.second { margin-top: 16px; }
/* and, for the display section below: */
.chip { width: 120px; margin-top: 40px; }
.chip-inline-block { display: inline-block; }const p1 = document.getElementById('p1').getBoundingClientRect();
const p2 = document.getElementById('p2').getBoundingClientRect();
console.log('gap = ' + (p2.top - p1.bottom).toFixed(1) + 'px');gap = 24.0px (the larger of 24px and 16px, not their sum)04. display: what kind of box is this?
display decides which layout rules apply to an element. The three values to know cold:
blocktakes the whole line, honourswidth, and grows vertically with its content.inlineflows with text like a word. Width, height and vertical margins are ignored — its size comes from its content and the line's line-height. Horizontal margins and padding work but do not push neighbouring lines apart.inline-blockflows like a word but sizes like a block:width,heightand vertical margins all take effect. It is the standard answer for badges and chips that sit in a line of text yet need real dimensions.
Two more belong in your vocabulary: none removes the box entirely from rendering and from the accessibility tree (use hidden for the same effect with less CSS), and the flex and grid values switch the element's children over to those layouts — a bigger topic than this lesson.
const rect = (id) => document.getElementById(id).getBoundingClientRect();
const line = (id) => document.getElementById(id).getBoundingClientRect();
console.log('inline width 120? = ' + (rect('chip1').width === 120));
console.log('inline-block width = ' + rect('chip2').width + 'px');
console.log('inline drop = ' +
(line('chip1').top - line('line-inline').top).toFixed(1) + 'px');
console.log('inline-block drop = ' +
(line('chip2').top - line('line-iib').top).toFixed(1) + 'px');inline width 120? = false (width: 120px was ignored)
inline-block width = 120px
inline drop = 0.0px (margin-top: 40px was ignored)
inline-block drop = 40.0pxThe inline chip is only as wide as the word "new" — about 27 pixels in Chromium's default serif font on the test machine, a little different with other fonts, which is why the snippet only checks whether the width is 120. The browser flags the ignored width directly: the Styles panel will show width: 120px in pale, dimmed text with an info icon (an inactive CSS declaration) on an inline element — declared, but having no effect. The Computed panel tells the truth: an inline box has no width of its own to compute. When a size or a vertical margin "does nothing", check display before checking anything else.
05. position: taking a box out of flow
Positioning moves a box relative to some reference point, chosen by the position value:
relativestays in flow, buttop/right/bottom/leftthen offset the box visually from where flow put it — the original space is kept. It also makes the element the reference box for positioned descendants, which is its most common job.absoluteremoves the box from flow and places it against the nearest positioned ancestor — an ancestor with any position other thanstatic. With no such ancestor it falls back to the initial containing block (the page). Inset values then work like coordinates.fixedremoves it from flow and positions it against the viewport, so it does not scroll with the page — unless an ancestor has atransform,filterorperspective(orcontain: paint). That ancestor then becomes the reference box, and the "fixed" element scrolls with it: a classic bug for a fixed modal inside an animated wrapper.stickystays in flow until a scroll would carry it past an inset you set, then holds still — within its nearest scrolling ancestor.
Overlapping boxes are painted in DOM order, then by z-index for positioned or flex/grid children. z-index has no global power: it only compares within the same stacking context, and certain properties (a transform, an opacity below 1, a filter) silently create one. When an element "will not go behind", look for an accidental stacking context before raising numbers.
.card { position: relative; } /* the reference box */
.badge {
position: absolute;
top: 0;
right: 0; /* pin to the card's top-right corner */
}const card = document.getElementById('card').getBoundingClientRect();
const badge = document.getElementById('badge').getBoundingClientRect();
console.log('badge inset right = ' + (card.right - badge.right) + 'px');
console.log('badge inset top = ' + (badge.top - card.top) + 'px');badge inset right = 0px (flush with the card edge)
badge inset top = 0pxDrop position: relative from the card and the same insets measure against the page instead — the badge lands in the browser window's top-right corner. That single missing keyword is one of the most common positioning bugs in real stylesheets.
Sticky has its own trap: it sticks within its nearest scrolling ancestor, and overflow: hidden on any ancestor quietly becomes that ancestor. A sticky header inside such a box will scroll away with the rest, because its reference never actually scrolls. To see it, give a scroller a 1-pixel border and a sticky header, scroll it 120 pixels and compare the two top values: when sticking works, the header's top sits just inside the scroller's border. Keep the overflow on the true scroller and it keeps working; put it on an outer wrapper and it stops.
06. Check your understanding
07. Apply it
Return to the article page you styled in the first lessons and give it a real layout pass. Switch the whole stylesheet to border-box with the reset line, then build the page frame from normal flow alone — header, article, footer — and only reach for position: absolute once, for a skip link or a badge, remembering the relative on its parent. Measure three things in the console: the outer width of a box with known padding and border, the gap between two blocks with competing margins, and the coordinates of your absolutely positioned element. Each measurement should match what you predicted from this lesson; where it does not, the DevTools box model diagram will show you which layer of the box you miscounted. These are exactly the senses you will sharpen in the debugging lab later in this skill.
08. Review prompt
Without looking back: in the default content-box model, write the formula for a box's outer width from width, padding and border, then rewrite it for border-box. Name the three display values and say which ignore width and vertical margins. Recite what relative, absolute, fixed and sticky each measure their insets against, and give two properties that accidentally create a stacking context.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.