Lesson 2 of 12 · 11 min · HTML and CSS

CSS fundamentals and the box model

Covers: Current CSS specifications. Updated 13 Nov 2026. Part of the Frontend Developer roadmap.

What you will learn

  • Write CSS rules and connect them to HTML
  • Selectors, specificity and the cascade
  • The box model: content, padding, border and margin
  • box-sizing: border-box and margin collapsing
  • Units (px, rem, %, vw) and the display property

In simple words

If HTML is the skeleton, CSS is the clothes and the layout. Every element on a web page is drawn as a rectangular box. The box model describes that box: the content in the middle, some padding around it like cushioning, a border like a frame, and then margin, the empty space between this box and its neighbours. Almost every layout problem comes down to understanding these boxes.

Words to know

  • Selector: the part of a CSS rule that chooses which elements to style.
  • Declaration: one property and value, such as color: navy;.
  • Cascade: the rules that decide which style wins when several apply.
  • Box model: the content, padding, border and margin that make up each element's box.

A CSS rule

/* selector { property: value; } */
h1 {
  color: #1e3093;
  font-size: 2rem;
}

Connect CSS to HTML with a stylesheet link in <head> (the best choice: cached and reusable):

<link rel="stylesheet" href="styles.css">

You can also use a <style> element or an inline style="..." attribute, which are harder to maintain.

Selectors

Selector Matches
p all <p> elements (type selector)
.card elements with class="card"
#header the element with id="header" (ids must be unique)
a[href^="https"] attribute selector
nav a a link anywhere inside a nav (descendant)
ul > li li directly inside ul (child)
h2 + p a p right after an h2 (adjacent sibling)
a:hover, button:focus-visible pseudo-classes (states)
li:nth-child(2n) structural pseudo-classes
p::first-line, .btn::after pseudo-elements
.card:has(img) a .card that contains an img (the "parent selector", supported by all current browsers)
.a, .b either

Modern CSS also supports nesting without a preprocessor:

.card {
  padding: 1rem;
  & h2 { margin: 0; }
  &:hover { box-shadow: 0 2px 8px rgb(0 0 0 / 0.15); }
}

The cascade and specificity

When two rules target the same property of the same element, CSS decides the winner by, in order: importance (!important, avoid it), specificity, then source order (the later rule wins). Specificity counts, from highest to lowest: inline styles, ids, then classes, attributes and pseudo-classes, then element types.

p { color: black; }              /* specificity 0,0,1 */
.note { color: gray; }           /* 0,1,0  wins over p */
#intro { color: navy; }          /* 1,0,0  wins over .note */

Tips: style with classes (low, even specificity), avoid ids for styling and !important, keep selectors short, and use @layer to order groups of styles (reset, base, components, utilities) so that layer order beats specificity. Naming conventions such as BEM (.card__title--large) keep a large stylesheet predictable. Some properties are inherited by children (color, font-family, line-height) and some are not (margin, border, background).

The box model

Every element is a rectangle made of four layers, from the inside out:

+-------------------------------+  margin (outside, transparent)
|  +-------------------------+  |
|  |  border                 |  |
|  |  +-------------------+  |  |
|  |  | padding           |  |  |
|  |  |  +-------------+  |  |  |
|  |  |  |   content   |  |  |  |
|  |  |  +-------------+  |  |  |
|  |  +-------------------+  |  |
|  +-------------------------+  |
+-------------------------------+
.card {
  width: 300px;
  padding: 16px;                    /* space between content and border */
  border: 2px solid #ccc;           /* the frame */
  margin: 24px auto;                /* space outside; auto centres a block horizontally */
  background: white;                /* fills content, padding (and under the border) */
}

Shorthands take values clockwise from the top: padding: 8px 16px 8px 16px (top, right, bottom, left); two values mean (vertical, horizontal); one means all sides. Logical properties (margin-inline, padding-block) adapt to writing direction.

box-sizing decides what width means:

  • content-box (the browser default): width is the content only. A box with width: 300px; padding: 16px; border: 2px is 300 + 32 + 4 = 336px wide, which surprises everyone.
  • border-box: width includes padding and border, so the box is exactly 300px.

Almost every project starts with:

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

Margin collapsing and spacing

Vertical margins of adjacent block elements collapse: two paragraphs with margin-bottom: 20px and margin-top: 30px have 30px between them, not 50px (the larger wins). Margins of a parent and its first or last child can also collapse through the parent. Horizontal margins, margins in flex and grid layouts, and margins of floated or absolutely positioned elements do not collapse. Padding and borders never collapse.

Modern advice for spacing: prefer gap in flex and grid layouts for space between items, use padding for space inside, and use margin sparingly for space around.

Units

Unit Meaning Use for
px a CSS pixel borders, small fixed details
rem relative to the root font size (16px by default) font sizes and spacing, which respect user settings
em relative to the element's own font size spacing relative to text
% relative to the parent widths
vw, vh 1% of the viewport width or height full-screen sections; use dvh on mobile where the browser bar resizes
ch the width of the "0" character readable text widths (max-width: 65ch)
fr a share of free space in grid grid tracks

Use rem for font sizes, so that people who set a larger default text size in their browser get larger text (an accessibility need; fixed px font sizes ignore it). Functions help: clamp(1rem, 2.5vw, 1.5rem) (a font that scales between limits), min(), max(), calc(100% - 2rem).

Display and layout basics

The display property decides how a box behaves:

Value Behaviour
block starts on a new line, fills the width, accepts width and height (div, p, h1)
inline flows within text, ignores width, height and vertical margins (span, a, strong)
inline-block flows inline but accepts width and height
flex / grid the modern layout systems (next lesson)
none removes the element from the page (and from assistive technology)

visibility: hidden hides it but keeps its space. For content hidden only visually but still read by screen readers, use a "visually hidden" utility class (a clipped one-pixel box).

position (static, relative, absolute, fixed, sticky) takes an element out of the normal flow or pins it; z-index orders overlapping elements, but only within stacking contexts. Use it for badges, dropdowns and sticky headers, not for page layout.

Colour, text and backgrounds

body {
  font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
  font-size: 1rem;
  line-height: 1.6;                 /* unitless: 1.6 times the font size */
  color: #1a1a1a;
  background: #fbf8ff;
}
a { color: #1e3093; text-decoration-thickness: 0.08em; }
.btn { background: linear-gradient(#3949ab, #1e3093); border-radius: 999px; }

Colours can be written as names, hex (#1e3093), rgb(), hsl(), and modern oklch(). CSS custom properties (variables) keep a design consistent and let you theme:

:root { --brand: #1e3093; --space: 1rem; }
.btn { background: var(--brand); padding: var(--space); }
@media (prefers-color-scheme: dark) { :root { --brand: #9fa8ff; } }

Debugging with DevTools

Open the browser developer tools (F12). The Elements panel shows the DOM and, for the selected element, the applied CSS (with overridden rules struck through) and a box model diagram with its content, padding, border and margin sizes. Edit values live, toggle declarations, and use the "Computed" tab to see the final values. When something is "not applying", check the specificity and whether another rule overrides it.

Common mistakes

  • Forgetting box-sizing: border-box, so widths exceed the container.
  • Fixing layout with magic margins and fixed pixel heights.
  • High-specificity selectors and !important, which make later changes painful.
  • Using px for font sizes, ignoring user text settings.
  • Surprise margin collapsing, and using margin for gaps between flex items.
  • Hiding content with display: none that screen reader users need.
  • Not using the DevTools box-model view.

Try it yourself

  1. Create a .card with width 300px, padding 16px and a 2px border; measure its total width with content-box and border-box.
  2. Make two paragraphs with margins 20px and 30px and observe the 30px gap; then wrap them in a flex container and see the margins stop collapsing.
  3. Write rules with an id, a class and a type selector targeting one element and predict which colour wins.
  4. Set font sizes in rem and change the browser's default font size to see the page scale.
  5. Define colour and spacing variables in :root and use them in three rules.

Check yourself

What are the four layers of the box model from inside to outside?

Content, padding, border and margin.

What does box-sizing: border-box change?

The width and height then include padding and border, so the box's total size equals the value you set.

Which wins: .note { color: gray } or p { color: black } on <p class="note">?

The class rule, because a class selector has higher specificity than a type selector.

What is margin collapsing?

Adjacent vertical margins of block elements combine into one margin equal to the larger of them, instead of adding up.

Interview questions

Explain the CSS box model.

Every element is a box with content, surrounded by padding, then a border, then margin. With content-box sizing, width covers only the content; with border-box, it includes padding and border. Margins separate boxes and can collapse vertically.

How is specificity calculated?

By counting selector types: inline styles beat ids, ids beat classes, attributes and pseudo-classes, which beat element types; with a tie, the later rule wins. !important overrides normal specificity.

What is the difference between rem and em?

rem is relative to the root element's font size, so it is predictable; em is relative to the current element's font size, so nested elements compound.

Summary

  • A CSS rule is a selector and declarations; the cascade chooses the winner by importance, specificity and order.
  • Every element is a box: content, padding, border, margin; use box-sizing: border-box.
  • Use rem, %, clamp() and gap; know display values and basic positioning.
  • Use custom properties for consistency and DevTools to inspect boxes.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on HTML, CSS and how the web works for Frontend Developer and scores every answer, with what to fix.