Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Concept · 25 min · revision 3

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

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): width sets the content only. The visible box adds padding and border on top, so it ends up wider than you asked.
  • border-box: width sets 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:

CSS · styles.css
.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;
}
HTML · index.html
<!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.

DevTools console
for (const id of ['cb', 'bb']) {
  const w = document.getElementById(id)
    .getBoundingClientRect().width;
  console.log(id + ' outer width = ' + w + 'px');
}
Expected output (notes in parentheses are not printed)
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.

CSS · styles.css
.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; }
DevTools console
const p1 = document.getElementById('p1').getBoundingClientRect();
const p2 = document.getElementById('p2').getBoundingClientRect();
console.log('gap = ' + (p2.top - p1.bottom).toFixed(1) + 'px');
Expected output (notes in parentheses are not printed)
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:

  • block takes the whole line, honours width, and grows vertically with its content.
  • inline flows 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-block flows like a word but sizes like a block: width, height and 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.

DevTools console
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');
Expected output (notes in parentheses are not printed)
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.0px

The 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:

  • relative stays in flow, but top/right/bottom/left then 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.
  • absolute removes the box from flow and places it against the nearest positioned ancestor — an ancestor with any position other than static. With no such ancestor it falls back to the initial containing block (the page). Inset values then work like coordinates.
  • fixed removes it from flow and positions it against the viewport, so it does not scroll with the page — unless an ancestor has a transform, filter or perspective (or contain: 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.
  • sticky stays 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.

CSS · styles.css
.card { position: relative; }        /* the reference box */
.badge {
  position: absolute;
  top: 0;
  right: 0;   /* pin to the card's top-right corner */
}
DevTools console
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');
Expected output (notes in parentheses are not printed)
badge inset right = 0px   (flush with the card edge)
badge inset top   = 0px

Drop 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

Practice check · 3 questions

Boxes in practice

Predict sizes, gaps and placement before reading the reasoning.

Q1. A card has `box-sizing: border-box; width: 300px; padding: 10px; border: 2px solid;`. How wide is its content area?
Q2. Two cards sit inside a `display: flex; flex-direction: column` container. The top card has `margin-bottom: 30px;` and the bottom card has `margin-top: 12px;`. How much space separates them?
Q3. A modal overlay has `position: fixed; inset: 0`, yet it covers only its wrapper and scrolls away with the page. The wrapper has `transform: translateY(0)` from an entrance animation. What is going on?
Practice only: not graded, not saved, not evidence.

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.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check