Paperlark's first page
This track builds one site from the bottom up: Paperlark, an invented online stationery shop. Customers browse notebooks and pens, add them to a basket and check out. The track starts where every page starts, with styles, because most of the surprises in a front-end codebase are not in the JavaScript. They are in the sentence "I set the width to 200 pixels, so why is it 250?" and in the rule that "does nothing" because another rule won.
Three ideas carry most of that: every element is a box with four layers, boxes are laid out in a default order called normal flow, and when two rules disagree the cascade picks one by a fixed procedure. This chapter covers all three. The numbers quoted were measured, not calculated: a test page with the exact styles shown was opened in Chrome 152, and sizes were read back with getBoundingClientRect() and getComputedStyle(). Text widths depend on the font, so where one appears the chapter says "about".
The box model and box-sizing
Every element on the page is drawn as a rectangle made of four layers, from the inside out: the content, the padding around it, the border around that, and the margin outside the border. Padding and the content share the element's background. The margin is empty space that keeps other elements away.
Take the product card on Paperlark's front page:
.card {
width: 200px;
padding: 20px;
border: 5px solid #333;
margin: 10px;
}
You might expect a card 200 pixels wide. The measured width of the border box is 250 pixels. By default width sets the size of the content only, so the card is 200 of content, plus 20 of padding on each side (40), plus 5 of border on each side (10): 200 + 40 + 10 = 250. The 10 pixels of margin are outside that rectangle, so the card takes 270 pixels of room in a row.
That default is called content-box, and it makes percentages awkward. A column with width: 50% and some padding ends up wider than half. The usual remedy is the other model, border-box, where width covers the content, padding and border together:
.card-bb {
box-sizing: border-box;
width: 200px;
padding: 20px;
border: 5px solid #333;
margin: 10px;
}
Now the measured border box is exactly 200 pixels, and the content is what is left: 200 - 40 - 10 = 150. Most projects set box-sizing: border-box for every element once, at the top of the stylesheet, so a width means what it says. It is not inherited, which is why the rule is usually written for * or for each element, not just html.
The usual reset is three selectors long and goes at the very top of the stylesheet:
*, *::before, *::after {
box-sizing: border-box;
}
Browser developer tools draw the same four layers for any element you select, with the numbers in each layer, which is the quickest way to find out where 250 pixels came from.
Two practical points. Percentages for padding and margin are always taken from the width of the containing block, even for the top and bottom sides. And the margin is never part of an element's background or border box; if a background seems to stop short of a gap, the gap is margin.
Margins that collapse
Vertical margins behave in a way that surprises almost everyone once. When two block elements are stacked, their touching vertical margins do not add. They collapse into one margin, as big as the larger of the two:
.sib { height: 40px; background: #ccc; }
.sib-a { margin-bottom: 30px; }
.sib-b { margin-top: 20px; }
Place .sib-a above .sib-b. The gap measured between them is 30 pixels, not 50. The 20 is swallowed by the 30.
The same collapsing happens between a parent and its first child when nothing separates them. If the parent has no padding, no border and no content before the child, the child's top margin escapes through the parent. A child with margin-top: 24px inside a plain parent does not sit 24 pixels below the parent's top edge. Measured, the child's top is 0 pixels from the parent's top, and the whole parent has moved down 24 pixels from the element before it. The space is still there; it just belongs outside.
Give the parent anything that blocks the collapse, even padding-top: 1px, and the child sits where you expected: its top is measured at 25 pixels from the parent's top, which is the 1 of padding plus the 24 of margin.
Margins do not collapse in some places: between flex or grid items, around floats and absolutely positioned boxes, and when the parent creates its own formatting context. Measured: with overflow: hidden or display: flow-root on the parent, the first child's 24 pixel margin stays inside, 24 pixels below the parent's top edge. In a column flex container the same two siblings measure 50 pixels apart, because the 30 and the 20 add up.
When spacing is hard to predict, use gap in flex and grid layouts, or put the space on one side only (for instance, always margin-bottom). Both avoid collapsing as a source of surprise.
Normal flow: block, inline and inline-block
Before any layout rule is written, the browser puts boxes in normal flow. Block boxes (div, p, section, h1) stack top to bottom, and each one is as wide as its container leaves room for. In a 600-pixel container, a plain div measures 600 pixels wide even if its text is a single word.
Inline boxes (span, a, strong) sit inside lines of text and run left to right. The surprising part is what an inline box ignores. Give a span width: 300px and height: 80px and it still measures only as wide as its text, about 57 pixels for the word "inline" in the test font, and a line high, 17 pixels. Horizontal padding and margin work; vertical padding paints but does not push neighbours away; width and height do nothing.
display: inline-block sits between the two. The box flows with text like an inline, and takes width, height and vertical margins like a block:
.ib { display: inline-block; width: 100px; height: 40px; }
Put three .ib elements in a row. If the HTML has whitespace between the first two, the browser treats it as a space character between words, and the boxes are about 4 pixels apart. Where the tags touch with nothing between them, the gap is 0. This is the oldest source of a mystery gap in a row of buttons. Modern layouts avoid it with flexbox, and the display value to remember for rows is flex.
Images are inline by default too, and that causes a classic puzzle. A 100 by 50 image alone inside a div makes the div 54 pixels high when measured, not 50: the image sits on the text baseline, and the line box keeps room for letters that hang below it. The extra space depends on the font. Setting the image to display: block made the same div exactly 50 pixels high. If a gap appears under an image, this is nearly always why.
Three habits fall out of this. Use block elements for sections, inline elements for words inside them, and flex or grid for arranging boxes in a row or a grid. Do not give an inline element a size and wonder why it ignores it. And when something refuses to centre or to take a margin, ask first what its display value is.
The cascade: which rule wins
A page nearly always has more than one rule for the same property of the same element: the browser's defaults, the site's stylesheet, a component's stylesheet, a style attribute. The cascade is the procedure that picks one winner per property. It compares the competing declarations in a fixed order, and the first test that finds a difference decides:
- Importance and origin. A declaration marked
!importantbeats a normal one. Author styles beat the browser's defaults. - Specificity. The more specific selector wins.
- Order. If everything else is equal, the rule that comes later in the source wins.
Modern CSS adds one more step before specificity: cascade layers. For normal declarations, rules written inside @layer blocks lose to rules written outside any layer, whatever their specificity (for !important declarations the order is inverted). Measured: a layered rule #lay p with an ID in its selector lost to an unlayered p.lay2 with only a class and an element. Layers exist so that a framework's styles can be put in a layer and the shop's own styles always win without any specificity arms race.
Order is only the last tie-breaker. A rule written at the bottom of the file does not beat a more specific rule written above it.
Some properties are also inherited. If an element has no rule for an inherited property, it takes its parent's value. Text properties inherit: color, font-family, line-height. Box properties do not: border, margin, padding, background. Measured on a div with color: rgb(50, 60, 70) and a 3 pixel border, the span inside it reports the same colour and a border width of 0.
!important jumps the specificity step, and that is why it is a trap. A declaration with !important can only be beaten by another !important declaration that wins the same comparison (higher specificity, an earlier layer, or the same score and later in the source), or by the browser's own or the user's !important rules, so one use leads to the next. Reserve it for rules that must hold whatever the context, such as a utility class that hides an element, and never use it to win an argument with your own stylesheet.
When a style does not apply, the Styles panel of the browser's developer tools shows every rule that matches the element, in the order of the cascade, with the losing declarations crossed out and the file and line each came from. That panel answers the question "who won?" faster than reasoning does, so open it before changing a selector.
Specificity by counting
Specificity is a score that every selector has, written as three numbers: the count of ID selectors, the count of class, attribute and pseudo-class selectors, and the count of element and pseudo-element selectors. Compare the first numbers, then the second, then the third. The numbers never carry over: eleven classes on one element still lose to one ID, which was measured with that exact page.
.t1 p { color: rgb(0, 0, 255); }
.t1 .note { color: rgb(255, 0, 0); }
#t1id p { color: rgb(0, 128, 0); }
For <p class="note"> inside <div class="t1" id="t1id">, the three scores are .t1 p = (0,1,1), .t1 .note = (0,2,0) and #t1id p = (1,0,1). The ID selector has the first number, so it wins and the paragraph is green (rgb(0, 128, 0) when measured). The red rule has more classes but classes only count when the IDs tie.
When the scores tie exactly, source order decides:
.t2 .a { color: rgb(1, 1, 1); }
.t2 .b { color: rgb(2, 2, 2); }
A paragraph with class="a b" is rgb(2, 2, 2). It does not matter that a comes first in the attribute; what counts is that the .b rule comes later in the stylesheet.
Two details help when you read other people's CSS. The universal selector * and combinators add nothing to the score. And :where() always counts as zero, while :is() takes the score of its most specific argument. Measured: a paragraph with class="g1" stays the colour of .g1, even though a :where(#wid) rule comes later, because the second rule's score is zero; and :is(.f1, #fid) scores like the ID in its list, so it beats a plain .f2 rule even on an element that has no fid id. That makes :where() the right tool for a base style that anything may override.
!important outranks all of it. With these two rules a paragraph in #t3id ends up rgb(10, 10, 10) even though the second rule has an ID:
.t3 p { color: rgb(10, 10, 10) !important; }
#t3id p { color: rgb(20, 20, 20); }
An inline style attribute also outranks selectors in a normal cascade: a paragraph with eleven classes and style="color: rgb(77, 77, 77)" measured rgb(77, 77, 77). That is why styles written into HTML are hard to override from a stylesheet.
One working rule keeps specificity under control across a codebase: style with single class selectors, keep IDs for anchors and scripts, and let the order of the stylesheet decide ties. A stylesheet where almost every selector scores (0,1,0) is easy to override on purpose and hard to override by accident. The trouble starts when one selector scores (1,2,1) because someone nested it deeply to make a style stick; everything that follows must then outbid it. If you inherit a stylesheet like that, flatten the winner instead of adding another layer on top.
Mistakes that recur
- Calculating widths as if
widthwere the whole box. Incontent-box, padding and border are added on top. Setbox-sizing: border-boxonce. - Chasing a "missing" margin that collapsed. Check whether the neighbour or the parent is swallowing it, and put the space on one side or use
gap. - Sizing an inline element.
widthandheighthave no effect on aspan; change itsdisplay. - Fixing a losing rule by raising specificity. Adding an ID or
!importantmakes the next override harder. Prefer a flatter selector in the right place. - Assuming the later rule always wins. It wins only when importance and specificity tie.
- Expecting borders and backgrounds to inherit. They do not; text properties do.
Carry forward: a box has content, padding, border and margin, and border-box makes width mean the whole box; vertical margins collapse unless something separates them; boxes follow block, inline or inline-block rules until you change display; and the cascade decides by importance, then specificity, then order. The next chapter turns to the JavaScript that makes the page respond.