FE·14
CSS
CSS from the cascade up: selectors, specificity, inheritance, layers, values and units, the layout algorithms (flow, flexbox, grid, positioning, stacking), responsive design, and modern CSS through 2026.
Start here: styling pages with CSS
Attaching CSS to a page
There are three places to put CSS, and real sites use the first:
<link rel="stylesheet" href="style.css"> <!-- 1. a separate file: shared by every page, cached -->
<style> h1 { color: #8a4b08; } </style> <!-- 2. a <style> block in this page -->
<p style="color: crimson">Sold out</p> <!-- 3. an inline style on one element: avoid -->
Rules: selectors and declarations
A CSS rule says "for these elements, set these properties":
.card h2 { /* selector: which elements */
color: #8a4b08; /* declaration: property: value; */
font-size: 1.25rem;
}
The selectors you'll use every day:
| Selector | Matches | Example |
|---|---|---|
p |
every <p> element (type selector) |
p { line-height: 1.5; } |
.card |
every element with class="card" |
elements can have several classes: class="card featured" |
#total |
the element with id="total" |
ids are unique per page; prefer classes for styling |
.card h2 |
<h2> elements inside a .card (descendant) |
|
.card > h2 |
<h2> elements that are direct children of a .card |
|
a:hover, input:focus |
elements in a state (pseudo-class) | |
h1, h2 |
either (a list) |
Classes are the workhorse: give elements meaningful class names (card, price, site-header) and style the classes.
Colours, sizes and units
- Colours: names (
crimson), hex (#8a4b08),rgb(138 75 8),hsl(30 89% 29%), or the neweroklch()(chapter's later sections). Add transparency with a fourth value:rgb(0 0 0 / 50%). - Absolute length:
px(a CSS pixel: about 1/96 inch at arm's length, not necessarily one screen dot). - Relative to text:
rem= the root font size (16 px by default),em= the current element's font size. Useremfor most sizes: when a user raises their browser's default font size, arem-based layout scales with it. - Relative to the container or screen:
%of the parent,vw/vhof the viewport.
The box model
Every element is a rectangular box with four layers, from the inside out: content, padding (space inside the border), border, and margin (space outside, separating it from neighbours).
By default, width sets only the content width, so padding and border are added on top: a "200 px" box with 20 px padding and a 5 px border is 250 px wide on screen (measured in Chromium in the lab). Nearly every site therefore starts its stylesheet with:
*, *::before, *::after { box-sizing: border-box; } /* width now includes padding and border */
Margins have one surprise: vertical margins between blocks collapse. Two paragraphs each with margin: 24px 0 are 24 px apart, not 48: the larger margin wins.
Block and inline
Elements flow in one of two basic ways, set by their display:
- Block (
<div>,<p>,<h1>,<section>,<ul>): starts on a new line and stretches across the full available width. Width, height, margins and padding all apply. - Inline (
<a>,<strong>,<span>,<em>): sits inside a line of text and is only as wide as its content. Width and height don't apply.
Layout systems (flexbox and grid, next) change how an element arranges its children.
Which rule wins: the cascade in three sentences
Often several rules set the same property on one element. The browser decides like this:
- Importance and origin:
!importantdeclarations beat normal ones (avoid writing them); your styles beat the browser's defaults. - Specificity: the more specific selector wins. Count, in order of strength, ids, then classes/attributes/pseudo-classes, then element names:
#total(1,0,0) beats.menu .price(0,2,0) beatsp.price(0,1,1) beatsp(0,0,1). Inlinestyle=""beats all selectors. - Order: if they're equally specific, the one that comes last wins.
Some properties, mostly text-related ones like color, font-family and line-height, are inherited: set them on body and every descendant gets them unless something overrides them. Layout properties like padding, border and width are not inherited.
When a style "doesn't work", the Styles pane in DevTools shows the losing declaration crossed out and, above it, the rule that beat it.
Flexbox: arranging things in a row or column
Flexbox lays children out along one line, with control over spacing and alignment. The classic site header, logo on the left and links on the right, vertically centred:
header {
display: flex; /* children become flex items in a row */
justify-content: space-between; /* spread along the row: first at the start, last at the end */
align-items: center; /* centre across the row (vertically) */
gap: 1rem; /* space between items */
}
flex-direction: column stacks items instead. Centring something in both directions, once notoriously hard in CSS, is display: flex; justify-content: center; align-items: center;.
Grid: rows and columns
Grid lays children out in two dimensions. Three equal columns of cards with gaps:
.cards {
display: grid;
grid-template-columns: repeat(3, 1fr); /* three columns, each one "fraction" of the space */
gap: 1rem;
}
Rough rule: flexbox for a row or column of things (toolbars, nav links, a card's inside), grid for a layout of rows and columns (page structure, card galleries, forms with aligned labels).
Responsive design: one page, every screen
Phones, tablets and laptops all load the same page. Media queries apply rules only when a condition holds, usually a minimum width. Start with the phone layout (single column) and add columns as space allows ("mobile-first"):
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sharma's Tiffin Centre</title>
<style>
:root { --brand: #8a4b08; }
* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, sans-serif; line-height: 1.5; color: #222; }
header { display: flex; justify-content: space-between; align-items: center;
padding: 1rem 1.5rem; background: var(--brand); color: white; }
header a { color: white; margin-left: 1rem; }
main { max-width: 60rem; margin: 0 auto; padding: 1.5rem; }
.cards { display: grid; grid-template-columns: 1fr; gap: 1rem; }
.card { border: 1px solid #ddd; border-radius: 0.75rem; padding: 1rem; }
.card h2 { margin: 0 0 0.25rem; font-size: 1.25rem; color: var(--brand); }
.price { font-weight: 700; }
@media (min-width: 40rem) { .cards { grid-template-columns: repeat(2, 1fr); } }
@media (min-width: 60rem) { .cards { grid-template-columns: repeat(3, 1fr); } }
</style>
</head>
<body>
<header><strong>Sharma's Tiffin</strong><nav><a href="/menu">Menu</a><a href="/visit">Visit</a></nav></header>
<main>
<h1>Breakfast</h1>
<div class="cards">
<article class="card"><h2>Masala dosa</h2><p>Crisp, with potato masala.</p><p class="price">₹90</p></article>
<article class="card"><h2>Idli (2)</h2><p>Steamed, with sambar.</p><p class="price">₹50</p></article>
<article class="card"><h2>Pongal</h2><p>Rice and lentils with pepper.</p><p class="price">₹70</p></article>
</div>
</main>
</body>
</html>
The same file measured in Chromium at a phone, a tablet and a laptop width:
viewport 375px: 1 column(s), card width 327px | card padding 16px | h2 colour rgb(138, 75, 8) | header height 56px
viewport 768px: 2 column(s), card width 352px | card padding 16px | h2 colour rgb(138, 75, 8) | header height 56px
viewport 1280px: 3 column(s), card width 293px | card padding 16px | h2 colour rgb(138, 75, 8) | header height 56px
Check the arithmetic: at 375 px the card is 375 − 2 × 24 px of main padding = 327 px. At 1280 px, main stops growing at 60 rem = 960 px, so three cards share 960 − 48 − 2 × 16 (gaps) = 880 px, about 293 px each. Two more things to notice: --brand is a custom property (a CSS variable), defined once in :root and used with var(--brand), so changing the brand colour is a one-line edit; and 1rem of padding became 16 px because the root font size is 16 px.
How deep to go in CSS
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Name selectors, units, the box model, flexbox and grid |
| L2 | Build responsive layouts with flexbox, grid, custom properties and media queries |
| L3 | Explain the cascade (origins, layers, specificity, order), inheritance, formatting contexts, containing blocks, stacking contexts and how flex and grid size items |
| L4 | Diagnose "my style doesn't apply", overflow, collapsing margins, z-index and layout bugs with DevTools |
| L5 | Design a CSS architecture: tokens, layers, component styles, container queries, theming |
| L6 | Keep a large codebase's CSS consistent, fast and accessible across teams and browsers |
How CSS decides a value
Rules, selectors and declarations
CSS is a declarative language (Vol. 1 ch. 2): you state what styles apply to which elements, and the engine works out the result. A stylesheet is a list of rules:
/* selector { property: value; ← declaration } */
.card > h2.title { font-size: 1.25rem; color: var(--ink); }
@media (width >= 48rem) { .card { padding: 2rem; } } /* at-rules: @media @supports @layer @container @font-face @keyframes @property @scope */
For every element and every one of several hundred CSS properties, the browser must produce exactly one value. CSS defines the pipeline:
- Declared values: every declaration whose selector matches the element.
- Cascaded value: the one that wins the cascade.
- Specified value: the cascaded value, or if there is none, the inherited value (inherited properties) or the initial value.
- Computed value: relative values resolved where possible (
2em→32px,currentColorresolved). - Used value: after layout (
width: 50%→412.5px). - Actual value: after device rounding.
getComputedStyle() returns the resolved value, which is the computed or used value depending on the property. DevTools' Computed pane shows which declaration won and why.
Selectors
| Selector | Matches | Example |
|---|---|---|
| Type | Elements by tag | button |
| Class | class contains the word |
.primary |
| ID | id equals |
#checkout (avoid in stylesheets: very high specificity) |
| Attribute | Attribute presence or value | [disabled], [type="email"], [href^="https"], [data-state="open"], [lang\|="en"] |
| Universal | Everything | * |
| Descendant | Any depth inside | nav a |
| Child | Direct child | ul > li |
| Next sibling | Immediately after | h2 + p |
| Subsequent sibling | Any later sibling | h2 ~ p |
| Pseudo-class | State or structure | :hover, :focus-visible, :checked, :nth-child(2n of .row), :not(), :is(), :where(), :has() |
| Pseudo-element | A part of an element | ::before, ::after, ::placeholder, ::marker, ::selection, ::backdrop |
Browsers match selectors right to left. For nav ul li a, the engine starts at each a and walks up the ancestors to check the rest. The rightmost part (the key selector) decides how many elements are candidates. Selector performance rarely matters today, except for very large DOMs combined with broad :has() selectors that are invalidated often.
Specificity
When two declarations for the same property match the same element, at the same origin and layer and importance, the more specific selector wins. Specificity is a three-part tuple (A, B, C), compared left to right:
- A: number of ID selectors.
- B: number of class selectors, attribute selectors and pseudo-classes.
- C: number of type selectors and pseudo-elements.
*and combinators count nothing.:is(),:not()and:has()take the specificity of their most specific argument.:where()always counts zero.
| Selector | Specificity |
|---|---|
p |
(0, 0, 1) |
.card p |
(0, 1, 1) |
.card .title |
(0, 2, 0) |
#checkout .btn |
(1, 1, 0) |
ul#nav li.active a:hover |
(1, 2, 3) |
:is(#a, .b) p |
(1, 0, 1), from #a |
:where(#a, .b) p |
(0, 0, 1) |
style="…" attribute |
beats any selector |
(1, 0, 0) beats (0, 99, 99): it's not base-10 arithmetic. If specificity ties, the declaration later in source order wins.
Specificity wars (escalating #id .x .y selectors and !important to override them) are the main cause of unmaintainable CSS. Modern defences: keep selectors flat (a single class, as in BEM or utility classes), use :where() for zero-specificity defaults, use cascade layers (below), and use CSS Modules or scoped styles (chapter 21).
The cascade
The cascade sorts competing declarations by these criteria, in order. The first difference decides:
- Origin and importance: transitions >
!importantuser-agent >!importantuser >!importantauthor > animations > normal author > normal user > normal user-agent.!importantreverses the origin order, so a user's!importantaccessibility styles beat the author's. - Context: for encapsulated content (shadow DOM), outer context vs inner.
- Element-attached styles: the
styleattribute. - Cascade layers: for normal declarations, later layers win, and unlayered styles beat all layers. For
!important, the order reverses. - Specificity.
- Scope proximity: within
@scope, the closer scope root wins. - Source order: last wins.
p { color: blue !important; }
#intro p { color: red; } /* loses despite higher specificity: importance is checked first */
Treat !important as an escape hatch. Legitimate uses are utility classes that must always win (.visually-hidden) and user stylesheets.
Inheritance
Some properties are inherited: if an element has no cascaded value, it takes its parent's computed value. Text properties mostly inherit (color, font-*, line-height, letter-spacing, text-align, visibility, cursor, direction, custom properties). Box properties mostly don't (margin, padding, border, width, background, display, position). That's why you set font-family and color once on body, but every box gets its own padding.
Explicit CSS-wide keywords work on every property:
| Keyword | Value used |
|---|---|
inherit |
The parent's computed value |
initial |
The property's spec-defined initial value (display: initial is inline, not block!) |
unset |
inherit if the property inherits, otherwise initial |
revert |
Roll back to the user-agent (browser default) style, or the user style |
revert-layer |
Roll back to the value from the previous cascade layer |
button { font: inherit; color: inherit; } /* form controls don't inherit fonts by default */
.reset-all { all: revert; } /* undo author styles on a subtree */
Cascade layers
@layer lets you create named layers whose order beats specificity. A weak selector in a later layer overrides a strong selector in an earlier one. That ends specificity wars between resets, third-party CSS, components and utilities:
@layer reset, base, vendor, components, utilities; /* declare the order once, up front */
@layer reset { *, *::before, *::after { box-sizing: border-box; margin: 0; } }
@layer base { a { color: var(--link); } }
@import url("datepicker.css") layer(vendor); /* put third-party CSS in a low layer */
@layer components { #sidebar .nav a { color: var(--ink); } } /* high specificity… */
@layer utilities { .text-accent { color: var(--accent); } } /* …still loses to this single class */
Unlayered CSS beats every layer, which is handy for gradual adoption, and a trap if you forget it. Tailwind v4 and many design systems ship their styles inside layers.
Pseudo-classes and pseudo-elements in practice
Pseudo-classes worth knowing well:
- User action:
:hover(guard it with@media (hover: hover)so touch devices don't get sticky hover),:active,:focus,:focus-visible(focus rings only when the browser judges them useful, such as keyboard focus; use it instead of removing outlines),:focus-within(a descendant has focus). - Form state:
:checked,:disabled,:required,:invalid,:user-invalid,:placeholder-shown,:autofill,:indeterminate. - Structure:
:first-child,:last-child,:only-child,:nth-child(an+b),:nth-of-type(),:empty,:root. - Logic:
:is()(match any, with max specificity),:where()(match any, zero specificity),:not()(accepts complex selector lists), and:has()(covered under modern CSS below). - Others:
:target(the element whose id matches the URL fragment),:popover-open,:modal,:open(details, dialogs, selects).
Pseudo-elements create styleable parts that don't exist in the DOM: ::before and ::after (need content, and are often used for decorative icons and overlays; content in them is announced by some screen readers, so don't put meaningful text there), ::marker (list bullets), ::placeholder, ::selection, ::first-line, ::first-letter, ::backdrop (behind modal dialogs and fullscreen elements), ::file-selector-button, and ::view-transition-*.
Values and units
Value types and units
| Category | Units | Relative to |
|---|---|---|
| Absolute | px (1/96 inch, a CSS pixel, not a device pixel), cm, mm, in, pt |
— |
| Font-relative | rem |
Root element's font size (usually 16 px) |
em |
The element's own font size (or the parent's, when used in font-size). Compounds when nested |
|
ch, ex, lh, rlh, cap, ic |
Width of "0", x-height, line height, cap height, CJK glyph | |
| Viewport | vw, vh, vmin, vmax |
1% of the viewport |
svh / lvh / dvh (also svw…) |
Small / large / dynamic viewport: accounts for mobile browser toolbars appearing and disappearing | |
| Container | cqw, cqh, cqi, cqb, cqmin, cqmax |
1% of the query container (container queries) |
| Percent | % |
The containing block, which depends on the property: width% uses the parent's width, padding-top: 10% also uses width, height% needs a definite parent height |
| Flexible | fr |
A fraction of leftover space in grid |
| Other types | deg/turn, s/ms, dppx, <color>, <image> (gradients), <string>, <url> |
Practical guidance:
- Use
remfor font sizes and most spacing, so the layout scales when users raise their browser's default font size (WCAG 1.4.4). A rootfont-size: 62.5%hack breaks users' own settings and gains nothing. - Use
emfor things that should scale with the component's own text, such as padding inside a button, or icons sized1em. - Use
chto limit line length:max-width: 65ch. - On mobile,
100vhis wrong for full-height layouts, because it includes the area behind the URL bar. Use100dvh, ormin-height: 100svh. pxis fine for borders, hairlines and shadows.
Custom properties
Custom properties (CSS variables) are properties you define, prefixed with --. They cascade and inherit like normal properties and are read with var():
:root {
--space-2: 0.5rem;
--radius: 8px;
--accent: oklch(55% 0.12 190);
}
.card { padding: var(--space-2); border-radius: var(--radius); }
.card.danger { --accent: oklch(55% 0.18 25); } /* re-scope for a subtree */
.card a { color: var(--accent); } /* resolves per element */
.btn { color: var(--btn-fg, white); } /* fallback if undefined */
Unlike Sass variables, which are compile-time constants, custom properties are live at run time. They change per element, per media query, per theme, and through JavaScript (el.style.setProperty("--x", "40px")). They're the backbone of theming and design tokens (chapter 21), and of dark mode:
:root { --bg: #fff; --fg: #111; color-scheme: light; }
@media (prefers-color-scheme: dark) { :root { --bg: #111; --fg: #eee; color-scheme: dark; } }
body { background: var(--bg); color: var(--fg); }
@property registers a custom property with a type, an initial value and an inheritance flag. Typed properties can then be animated (a gradient angle, for example), and invalid values fall back cleanly:
@property --angle { syntax: "<angle>"; inherits: false; initial-value: 0deg; }
.spinner { background: conic-gradient(from var(--angle), teal, transparent); animation: spin 1s linear infinite; }
@keyframes spin { to { --angle: 360deg; } }
Layout
The box model
Every element generates a box made of the content area, padding, border and margin.
The box-sizing property decides what width means:
content-box(the default):widthis the content only, so padding and border are added. Awidth: 100%with padding overflows its parent.border-box:widthincludes padding and border. Every modern reset sets*, *::before, *::after { box-sizing: border-box; }.
Margin collapsing: in normal flow, the vertical margins of adjacent blocks collapse into the larger of the two, not their sum, and a first child's top margin can escape through its parent. Margins don't collapse in flex or grid containers, nor across padding, borders, or a new block formatting context. This is a common source of "where did this space come from?" bugs. Using gap in flex and grid, or margin-block-start only on following siblings, avoids it.
Overflow: overflow: visible | hidden | clip | scroll | auto. hidden creates a scroll container (it can still be scrolled programmatically). clip truly clips and doesn't create one. overflow-wrap: anywhere and word-break handle long unbreakable strings such as URLs, which often overflow narrow layouts. Flex and grid items have min-width: auto by default, so they refuse to shrink below their content. Set min-width: 0 on them to let long content wrap or scroll instead of blowing out the layout.
Display and formatting contexts
display sets two things: the outer type (how the box participates in its parent's layout: block or inline) and the inner type (how it lays out its children: flow, flex, grid, table). display: flex means block flex, and inline-flex means inline flex.
Other values: none (no box at all, and removed from the accessibility tree), contents (the element's own box disappears and its children are promoted; historically it also stripped semantics from elements like buttons, which browsers have mostly fixed), flow-root (a block that establishes a new block formatting context: it contains floats and stops margins collapsing through it), and list-item.
A formatting context is an independent layout region. Block formatting contexts, flex formatting contexts and grid formatting contexts each isolate their children's layout from the outside, which is also what makes layout containment and performance optimisations possible (chapter 18).
Normal flow
Without flex, grid or positioning, elements lay out in normal flow:
- Block-level boxes stack vertically in the block direction, each taking the full available inline size by default.
- Inline-level boxes (text,
<a>,<span>,<img>,inline-block) flow horizontally in line boxes, wrapping at the container edge. Vertical margins and padding on inline boxes don't push lines apart.vertical-aligncontrols alignment within the line. Images are inline by default, which leaves a small gap below them for text descenders.display: blockon images fixes that.
"Horizontal" and "vertical" are really inline and block axes, which depend on the writing mode and direction. That's why logical properties (under modern CSS below) exist.
Floats (float: left) take a box out of flow and let text wrap around it. Today they're for exactly that, text wrapping around images, not for page layout. Contain floats with display: flow-root.
Flexbox
Flexbox lays items out along one axis, a row or a column, distributing space and aligning them. It's ideal for toolbars, nav bars, button groups, cards in a row, centring, and "push this to the end" layouts.
Container properties: flex-direction (row, column, and reversed versions), flex-wrap, justify-content (flex-start, center, space-between, space-around, space-evenly), align-items (stretch by default, plus center, baseline), align-content (for wrapped lines), and gap.
Item properties: flex: <grow> <shrink> <basis>, align-self, and order (which changes only the visual order, not focus or reading order, so be careful with accessibility).
How the flex algorithm sizes items: start each item at its flex-basis (auto means its width or content size). If there's free space, distribute it in proportion to flex-grow. If items overflow, shrink them in proportion to flex-shrink × basis, but never below their min-content size (because min-width: auto), unless you set min-width: 0.
| Shorthand | Means | Behaviour |
|---|---|---|
flex: initial |
0 1 auto |
Content-sized; can shrink, won't grow |
flex: auto |
1 1 auto |
Grows and shrinks from content size |
flex: 1 |
1 1 0% |
Equal shares of the space, regardless of content |
flex: none |
0 0 auto |
Rigid |
.toolbar { display: flex; align-items: center; gap: .5rem; }
.toolbar .spacer { margin-inline-start: auto; } /* pushes later items to the end */
.center { display: flex; place-content: center; } /* centre on both axes */
.cards { display: flex; flex-wrap: wrap; gap: 1rem; }
.cards > * { flex: 1 1 18rem; } /* wrap when narrower than 18rem each */
.sidebar-layout { display: flex; }
.sidebar-layout > main { flex: 1; min-width: 0; } /* min-width:0 lets long content wrap */
Grid
CSS Grid lays items out in two dimensions at once, rows and columns. It's for page layouts, card galleries, forms with aligned labels, dashboards, and anything where alignment across rows matters.
.page {
display: grid;
grid-template-columns: 16rem minmax(0, 1fr); /* sidebar + flexible main (minmax(0,…) avoids blowout) */
grid-template-rows: auto 1fr auto;
grid-template-areas:
"header header"
"nav main"
"footer footer";
min-height: 100dvh;
gap: 1rem;
}
.page > header { grid-area: header; }
.page > nav { grid-area: nav; }
.page > main { grid-area: main; }
.page > footer { grid-area: footer; }
@media (width < 48rem) {
.page { grid-template-columns: 1fr; grid-template-areas: "header" "main" "nav" "footer"; }
}
/* Responsive gallery with no media queries: as many 14rem+ columns as fit */
.gallery { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(14rem, 100%), 1fr)); gap: 1rem; }
Key concepts:
- Tracks are rows and columns, sized with lengths,
%,fr(fractions of leftover space),auto,min-content,max-content,minmax(min, max)andfit-content().repeat(auto-fill | auto-fit, …)creates as many tracks as fit.auto-fitcollapses empty tracks so the items stretch to fill the row. - Placement: by line numbers (
grid-column: 1 / -1spans everything), byspan n, by named areas, or by auto-placement (grid-auto-flow: row | column | dense). 1fris reallyminmax(auto, 1fr), so a long word or a wide<pre>inside can stretch the column. Useminmax(0, 1fr)for columns that must stay a fixed share.- Subgrid (
grid-template-columns: subgrid): a nested grid adopts its parent's tracks, so card titles, bodies and buttons line up across sibling cards. It's Baseline across major browsers. - Alignment:
justify-items/align-items(within cells),justify-content/align-content(the whole grid), andplace-*shorthands.
Flexbox or grid? Flexbox is content-out: items decide their size and the line adapts (one dimension). Grid is layout-in: you define the tracks and items fill them (two dimensions). Most real UIs use both: grid for the page and card layout, flex for the contents of each component.
Table layout
display: table and real <table> layout use the table algorithm: columns size to fit content across all rows, and table-layout: fixed makes it faster and more predictable (widths come from the first row and the column definitions). Use it for real tabular data (chapter 13). Grid has replaced table-based page layouts. For long data tables, position: sticky headers and overflow: auto wrappers are the standard pattern.
Positioning
position |
In flow? | Offsets (top/inset) relative to |
Typical use |
|---|---|---|---|
static (default) |
Yes | — (offsets ignored) | Everything |
relative |
Yes (space kept) | Its own normal position | Small nudges; creating a containing block for absolute children |
absolute |
No | The containing block: the nearest positioned ancestor's padding box | Badges, overlays, custom dropdowns |
fixed |
No | The viewport (unless an ancestor has a transform, filter or contain, which becomes the containing block instead, a famous gotcha) |
Toasts, persistent headers |
sticky |
Yes | Scrolls normally until its offset threshold, then sticks within its scroll container and parent | Table headers, section headings |
inset: 0 is shorthand for top/right/bottom/left: 0, which is handy for full-cover overlays. Sticky positioning fails silently when an ancestor has overflow: hidden or auto, which makes that ancestor the scroll container, or when the parent is no taller than the sticky element.
Anchor positioning (anchor-name, position-anchor, position-area, anchor() and position-try fallbacks) lets an absolutely positioned element tether to another element, such as a tooltip to its button, and flip automatically when it would overflow. It was previously the job of JavaScript libraries like Floating UI. It shipped in Chromium first and was an Interop 2025 target for the other engines. Combined with the Popover API (popover attribute and popovertarget, which put elements in the top layer with light dismiss), it covers menus and tooltips with little or no JavaScript.
Containing blocks
The containing block is the rectangle that percentages and offsets are resolved against, and which one applies depends on position:
- static or relative: the content box of the nearest block-level ancestor.
- absolute: the padding box of the nearest ancestor whose
positionisn'tstatic, or that has atransform,perspective,filter,contain: layout/paint,container-type, orwill-changefor those properties. - fixed: the viewport, unless an ancestor has
transform,filter,perspective,containand so on, which then contains it. That's why a "fixed" modal inside an animated (transformed) parent scrolls with the page. The top layer (<dialog>, popovers) escapes all of this.
Most "my absolute or fixed element is in the wrong place" bugs come down to identifying the containing block. In DevTools, the element's offset parent is shown in the box-model view.
Stacking contexts
Which element is painted on top? Within one stacking context, painting order is: background and borders → negative z-index children → in-flow blocks → floats → inline content → z-index: auto/0 positioned children → positive z-index children, by value.
z-index only compares elements within the same stacking context. A new stacking context is created by, among other things:
- The root element.
- A positioned element (
relative/absolute) withz-indexother thanauto.fixedandstickyalways create one. - A flex or grid item with a
z-index. opacity < 1,transform,filter,backdrop-filter,perspective,clip-path,mask,mix-blend-modeother than normal,isolation: isolate,contain: paint, andwill-changenaming any of these.
Fixes: put overlays at the end of <body> (portals in React and Angular), use the top layer (<dialog>, popover), which sits above everything regardless of z-index, define a small z-index scale as tokens, and use isolation: isolate deliberately to contain component z-indexes.
Responsive design
Mobile-first
Responsive design (Ethan Marcotte, 2010) means one codebase that adapts to every screen through fluid layouts, flexible media, and media queries. Mobile-first CSS writes the base styles for the smallest screen and adds complexity for larger ones with min-width queries:
.nav { display: none; } /* small screens: hidden behind a menu button */
@media (width >= 48rem) { .nav { display: flex; } .menu-button { display: none; } }
Why mobile-first? Small screens get the simplest CSS. You start with content priority rather than squeezing a desktop design down. Most traffic is mobile. Over-ridden desktop styles don't load on phones by accident.
Fluid design
Before reaching for breakpoints, let things flow:
- Widths in
%,frorflex, withmax-widthcaps (max-width: 72rem; margin-inline: auto). - Intrinsic layouts that adapt without queries:
repeat(auto-fill, minmax(…))grids,flex-wrapwith aflex-basis,clamp()for sizes. - Images and media with
max-width: 100%; height: auto. - Avoid fixed heights. Let content define the height.
Every Layout's "algorithmic layout" primitives (Stack, Cluster, Sidebar, Switcher) show how far intrinsic CSS can go without any media queries.
Breakpoints and media queries
Media queries apply styles conditionally:
@media (width >= 48rem) and (width < 75rem) { … } /* range syntax: Baseline, cleaner than min-/max-width */
@media (orientation: landscape) { … }
@media (hover: hover) and (pointer: fine) { … } /* mouse-like input: enable hover effects */
@media (pointer: coarse) { .btn { min-height: 44px; } } /* touch: bigger targets */
@media (prefers-color-scheme: dark) { … }
@media (prefers-reduced-motion: reduce) { … }
@media (prefers-contrast: more) { … }
@media (forced-colors: active) { … } /* Windows High Contrast */
@media print { nav, .ads { display: none; } }
Choose breakpoints where your content breaks, not by device catalogue: shrink the window until something looks wrong, then add a breakpoint there. Write them in em or rem so they respect user font size. Three or four breakpoints usually suffice (around 40, 48, 64 and 80rem). You can't use custom properties inside media query conditions.
Container queries
Media queries ask about the viewport. A reusable component needs to ask about the space it's actually given: a product card should switch to a horizontal layout when its container is wide, whether it's in a sidebar or the main column. Container queries do exactly that, and they're Baseline:
.card-slot { container-type: inline-size; container-name: card; } /* establish a query container */
.card { display: grid; gap: .75rem; }
@container card (inline-size >= 30rem) {
.card { grid-template-columns: 10rem 1fr; } /* side-by-side when the SLOT is wide */
}
.card h3 { font-size: clamp(1rem, 4cqi, 1.5rem); } /* container query units */
Style queries (@container style(--variant: compact)) query custom property values, and are supported in Chromium and Safari. Container queries are why component libraries can be truly layout-independent (chapter 21).
Responsive type
Make text scale smoothly between a minimum and a maximum with clamp(), rather than jumping at breakpoints:
:root { font-size: 100%; } /* respect the user's default (usually 16px) */
h1 { font-size: clamp(2rem, 1.2rem + 3vw, 3.5rem); } /* min, preferred (fluid), max */
p { font-size: clamp(1rem, .95rem + .25vw, 1.125rem); line-height: 1.6; max-width: 65ch; }
Always include a rem term in the preferred value. Pure vw sizes don't change when the user zooms, which fails WCAG resize-text requirements. Use text-wrap: balance for headings (it evens out line lengths) and text-wrap: pretty for paragraphs (it avoids orphan words). Variable fonts give fine control over weight and width with one file.
Responsive media
img, video, svg { max-width: 100%; height: auto; display: block; }
.hero { aspect-ratio: 16 / 9; object-fit: cover; width: 100%; } /* crop to fill without distortion */
.embed { aspect-ratio: 16 / 9; width: 100%; } /* responsive iframes */
Combine CSS with HTML srcset/sizes/<picture> (chapter 13), so small screens download small images, not just display them smaller. image-set() does the same for CSS background images.
Modern CSS
Nesting
Native CSS nesting is Baseline, so a preprocessor isn't needed for it:
.card {
padding: 1rem;
& .title { font-weight: 700; } /* .card .title */
&:hover { box-shadow: var(--shadow); }
&.is-active { outline: 2px solid var(--accent); }
.theme-dark & { background: #222; } /* .theme-dark .card */
@media (width >= 48rem) { padding: 2rem; }
}
Nested selectors behave like :is() for specificity, and current browsers accept nested type selectors without the &. Keep nesting shallow, at one or two levels. Deep nesting recreates the specificity and coupling problems of over-qualified selectors.
:has(), the parent selector
:has() matches an element based on its descendants or following siblings, something CSS couldn't do for 25 years. It's Baseline:
.card:has(img) { grid-template-rows: 12rem auto; } /* cards with an image */
form:has(:user-invalid) .submit { opacity: .6; } /* style a form by its fields' state */
label:has(+ input:required)::after { content: " *"; } /* label followed by a required input */
.field:has(input:focus-visible) { outline: 2px solid var(--accent); }
body:has(dialog[open]) { overflow: hidden; } /* lock scrolling while a modal is open */
li:has(+ li:hover) { transform: scale(1.05); } /* the *previous* sibling of the hovered item */
:root:has(#theme-toggle:checked) { --bg: #111; } /* state anywhere controls tokens globally */
It replaces a lot of "toggle a class from JavaScript" code. Its cost: the engine must re-check ancestors when descendants change. Browsers optimise common cases, but broad selectors on huge DOMs (*:has(…)) can be slow.
Logical properties
Logical properties describe layout in terms of the inline axis (the direction text runs) and the block axis (the direction lines stack), instead of left, right, top and bottom. Layouts then adapt automatically to right-to-left languages (Arabic, Hebrew, Urdu) and vertical writing modes (traditional Japanese and Chinese):
| Physical | Logical (in LTR, horizontal) |
|---|---|
margin-left / margin-right |
margin-inline-start / margin-inline-end |
margin-top / margin-bottom |
margin-block-start / margin-block-end |
padding-left + padding-right |
padding-inline |
width / height |
inline-size / block-size |
top/right/bottom/left |
inset-block-start … / inset-inline |
text-align: left |
text-align: start |
border-top-left-radius |
border-start-start-radius |
Set dir="rtl" on the <html> element for RTL languages, use logical properties everywhere, and an app mostly mirrors itself without separate stylesheets.
Math functions: calc, min, max, clamp
.sidebar { width: calc(100% - 2 * var(--gutter)); } /* mix units at run time */
.content { width: min(100% - 2rem, 70ch); } /* the smaller: fluid up to a cap, with gutters */
.hero h1 { font-size: clamp(2rem, 5vw + 1rem, 4rem); } /* clamp(MIN, PREFERRED, MAX) */
.tap { min-height: max(44px, 2.75rem); } /* the larger: never below 44px */
.round { width: round(up, 33.3%, 1px); } /* newer: round(), mod(), rem(), abs(), sign(), trig functions */
min() gives you a maximum size, and max() gives you a minimum, which trips everyone up at first. clamp(a, b, c) is max(a, min(b, c)). These functions often replace whole media queries.
Modern colour spaces
CSS colour has moved well beyond #rrggbb and rgb()/hsl() (which are sRGB):
oklch(L C H): perceptually uniform lightness (L 0–100%), chroma (C, colourfulness) and hue (H, degrees). Equal L steps look equally different, which HSL fails at: HSL yellow and blue at "50% lightness" look wildly different in brightness. OKLCH is ideal for design tokens and generated palettes (keep L and C fixed, rotate H for categorical colours with consistent contrast), and it can express wide-gamut P3 colours that modern displays show and sRGB can't.oklab(),lab(),lch(), andcolor(display-p3 1 0 0).- Relative colour syntax: derive colours from others:
oklch(from var(--accent) calc(l + 0.1) c h)for a lighter variant, orrgb(from var(--brand) r g b / 50%)for transparency. light-dark(light, dark): pick a value by the element'scolor-scheme. Theme tokens become one line each.
:root {
color-scheme: light dark;
--accent: oklch(52% 0.12 190);
--accent-hover: oklch(from var(--accent) calc(l - 0.06) c h);
--bg: light-dark(oklch(99% 0.005 190), oklch(18% 0.01 190));
--fg: light-dark(oklch(22% 0.02 190), oklch(93% 0.01 190));
}
Check contrast in OKLCH terms, but verify against WCAG's contrast ratio (chapter 20), which is still defined on sRGB luminance. APCA, a newer perceptual contrast model, is under discussion for future WCAG versions.
Colour mixing
color-mix() blends two colours in a chosen colour space:
.btn:hover { background: color-mix(in oklch, var(--accent), black 12%); } /* darken */
.badge { background: color-mix(in oklab, var(--accent) 15%, transparent); } /* tint */
.border { border-color: color-mix(in srgb, currentColor 25%, transparent); }
The interpolation space matters. Mixing blue and yellow in sRGB passes through a muddy grey, while OKLab and OKLCH give cleaner, perceptually even midpoints. Gradients accept the same choice: linear-gradient(in oklch, …).
Scroll-driven animations
Scroll-driven animations tie a CSS animation's progress to scroll position instead of time, and run on the compositor without JavaScript scroll handlers:
/* Reading progress bar */
.progress {
position: fixed; inset: 0 0 auto; height: 4px; background: var(--accent);
transform-origin: left;
animation: grow linear both;
animation-timeline: scroll(root block); /* progress = scroll position of the root scroller */
}
@keyframes grow { from { transform: scaleX(0); } to { transform: scaleX(1); } }
/* Fade cards in as they enter the viewport */
.card {
animation: reveal linear both;
animation-timeline: view(); /* progress = element's visibility in its scroller */
animation-range: entry 0% cover 30%;
}
@keyframes reveal { from { opacity: 0; translate: 0 2rem; } }
They shipped in Chromium first and arrived in Safari later (Safari 26). Firefox support is in progress, so use them as progressive enhancement with @supports (animation-timeline: scroll()), and respect reduced motion.
View transitions
The View Transitions API animates between two DOM states, or between two pages. The browser snapshots the old state, you change the DOM, and it crossfades or morphs between the snapshots using pseudo-elements you can style:
// Same-document (SPA): wrap the DOM update
document.startViewTransition(() => renderNewView());
/* Morph a thumbnail into the detail-page hero by giving both the same name */
.product-thumb, .product-hero { view-transition-name: product-42; }
::view-transition-old(root), ::view-transition-new(root) { animation-duration: 200ms; }
/* Cross-document (MPA) transitions: opt in on both pages, no JavaScript needed */
@view-transition { navigation: auto; }
Same-document transitions are Baseline. Cross-document transitions work in Chromium and Safari. React 19 adds a <ViewTransition> component on top of the API (chapter 22).
Reduced-motion support
Some users get nausea, vertigo or migraines from motion (vestibular disorders), and they set "reduce motion" in their OS. Respect it, as WCAG 2.3.3 recommends:
/* Option 1: opt everything down */
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}
/* Option 2 (better): only add motion when the user hasn't asked for less */
@media (prefers-reduced-motion: no-preference) {
.card { transition: transform .2s ease; }
html { scroll-behavior: smooth; }
}
Reduced motion doesn't mean no animation. Opacity fades are usually fine, while large movement, parallax, zooming and auto-playing video aren't. In JavaScript, check matchMedia("(prefers-reduced-motion: reduce)").matches before running animation libraries.
More modern CSS worth knowing
| Feature | What it does |
|---|---|
@scope (.card) to (.content) { … } |
Styles scoped to a subtree, with a lower boundary ("donut scope") |
@supports (display: grid) { … } / @supports selector(:has(a)) |
Feature queries for progressive enhancement |
aspect-ratio |
Intrinsic ratio boxes without padding hacks |
accent-color |
Theme native checkboxes, radios and range inputs in one line |
text-wrap: balance / pretty |
Nicer heading and paragraph line breaks |
field-sizing: content |
Auto-growing inputs and textareas |
interpolate-size: allow-keywords / calc-size() |
Animate to height: auto |
@starting-style + transition-behavior: allow-discrete |
Entry animations from display: none, and for popovers and dialogs |
content-visibility: auto + contain-intrinsic-size |
Skip rendering off-screen sections (chapter 27) |
scrollbar-gutter: stable |
Stop layout shift when scrollbars appear |
overscroll-behavior: contain |
Stop scroll chaining from modals to the page |
scroll-snap-type / scroll-snap-align |
Native carousels and paging |
Typed attr() |
Use attribute values as typed CSS values (newer, Chromium first) |
if() |
Inline conditionals on style or media queries (newest, Chromium first) |
Lab: the cascade and layout, measured
Each experiment below set a small page's HTML and CSS in Chromium 153 and read back what the browser computed (getComputedStyle) and where it put things (getBoundingClientRect). That's the most reliable way to settle any "which rule wins?" or "how wide will this be?" question: ask the engine.
Experiment 1: a cascade puzzle
Six rules compete for the color of three paragraphs, including two in cascade layers, an inline style and an !important:
<style>
@layer base, theme;
@layer theme { p.price { color: purple; } }
@layer base { #special { color: orange; } }
p { color: gray; }
.menu p { color: green; }
p.price { color: blue; }
.menu .price { color: teal; }
p.price { color: navy; }
</style>
<div class="menu">
<p class="price" id="special">₹90</p>
<p class="price" style="color: crimson">₹50</p>
<p>plain</p>
</div>
<style>.imp { color: black !important } p.imp { color: red }</style>
<p class="imp" style="color: lime">imp</p>
₹90 → rgb(0, 128, 128) teal
₹50 → rgb(220, 20, 60) crimson
plain → rgb(0, 128, 0) green
imp → rgb(0, 0, 0) black
Work through ₹90 the way the engine does:
- Origin and importance: all are normal author declarations, so go on.
- Layers: for normal declarations, unlayered styles beat every layer, and later layers beat earlier ones. So
#special(inbase) andp.price(intheme) are out, despite#specialhaving an id. Layers decide before specificity; that's their whole point: a design system can put its styles in a low layer and any unlayered app style overrides them without a specificity war. - Specificity among the unlayered candidates:
p(0,0,1),.menu p(0,1,1),p.price(0,1,1) twice,.menu .price(0,2,0). The highest is.menu .price: teal. The laterp.price { navy }loses even though it comes last, because order only breaks ties.
₹50 has an inline style, which beats any selector. "plain" isn't .price, so .menu p (0,1,1) beats p. And imp: !important beats even the inline style (an inline !important would beat it back). For !important, the layer order reverses, so a low layer's important declaration beats a high layer's: a deliberate escape hatch for design-system guarantees.
Experiment 2: box sizing and margin collapse
div { width: 200px; padding: 20px; border: 5px solid; margin: 10px; }
.bb { box-sizing: border-box; }
p { margin: 24px 0; }
content-box: rendered width 250px, computed width 200px
border-box: rendered width 200px, computed width 200px (content area 200 − 2×20 − 2×5 = 150px)
gap between two <p>s with margin 24px 0: 24px (not 48: vertical margins collapse)
getComputedStyle(el).width reports the value of the width property, so it's 200 px in both cases; only the rendered box (getBoundingClientRect) shows the difference. Margins collapse only between block boxes in normal flow, vertically. They don't collapse in flex or grid containers, for floats or absolutely positioned boxes, or across a parent that has padding, a border, or establishes a new block formatting context (display: flow-root is the clean way to make one).
Experiment 3: how flexbox divides space
.row { display: flex; width: 600px; }
.a { flex: 1 1 100px; } /* grow 1, shrink 1, basis 100px */
.b { flex: 2 1 100px; }
.c { flex: 0 0 100px; } /* rigid */
.row2 { display: flex; width: 300px; }
.row2 > * { flex: 1 1 200px; }
.row2 > .s { flex-shrink: 3; }
grow: a=200 b=300 c=100
shrink: x=175.0 y=125.0
Growing: the bases add up to 300 px, leaving 300 px free. It's shared by flex-grow ratio 1 : 2 : 0, so a gets 100 more and b 200 more. Shrinking works differently: the bases (400 px) overflow the 300 px row by 100 px, and the deficit is taken in proportion to flex-shrink × flex-basis: 1 × 200 for x and 3 × 200 for y, so x gives up 25 px and y 75 px. One more rule matters constantly in real layouts: flex items have min-width: auto by default, so an item won't shrink below its content's width; a long word or a wide table inside it overflows the row unless you set min-width: 0 on the item.
Experiment 4: auto-fill versus auto-fit
Two grids each hold only two items, with repeat(auto-fill, minmax(200px, 1fr)) and repeat(auto-fit, minmax(200px, 1fr)), measured at three container widths:
container 1000px auto-fill: 4 tracks, item width 238px | auto-fit: 4 tracks, item width 492px
container 700px auto-fill: 3 tracks, item width 223px | auto-fit: 3 tracks, item width 342px
container 400px auto-fill: 1 track, item width 400px | auto-fit: 1 track, item width 400px
Both create as many 200 px+ columns as fit (4 at 1,000 px: 4 × 200 + 3 × 16 gap = 848). auto-fill keeps the empty tracks, so two items sit in a row built for four; auto-fit collapses empty tracks to zero, so the two items stretch to fill the row. Use auto-fill for galleries that should look consistent whether they hold 2 items or 20, and auto-fit when a few items should use all the space.
Experiment 5: why z-index: 9999 lost
<style>
.box { position: absolute; width: 200px; height: 200px; }
.parent { position: relative; z-index: 1; opacity: .99; }
#big { z-index: 9999; left: 0; top: 0; }
#small { z-index: 2; left: 100px; top: 100px; }
</style>
<div class="parent"><div class="box" id="big"></div></div>
<div class="box" id="small"></div>
element on top at (150,150): #small
z-index only compares elements within the same stacking context. .parent creates one (positioned with a z-index; opacity below 1 would have created one by itself, as do transform, filter, isolation: isolate and several others). Everything inside it, z-index: 9999 included, is painted as a single layer at the parent's level, 1, which is below #small at 2. When a z-index "doesn't work", find the nearest ancestor that creates a stacking context (DevTools' 3D View/Layers panel shows them), or move the element into the top layer with <dialog> or the Popover API.
Experiment 6: :where, :is and the modern selectors
<style>
:where(#nav) a { color: red; } /* :where() adds zero specificity: (0,0,1) */
a { color: blue; } /* (0,0,1), later, so it beats the line above */
:is(#nav) a { color: inherit; } /* :is() takes its argument's specificity: (1,0,1) */
</style>
<nav id="nav" style="color: green"><a href="#">x</a></nav>
:where/:is → rgb(0, 128, 0)
:where() is how libraries write easily-overridable defaults; :is() shortens long selector lists. Two newer tools, measured the same way:
.slot { container-type: inline-size; }
.card { display: grid; grid-template-columns: 1fr; }
@container (min-width: 400px) { .card { grid-template-columns: 120px 1fr; } }
form:has(input:invalid) button { opacity: .4; }
card in a 280px sidebar slot: grid-template-columns 280px (stacked)
card in an 800px main slot: grid-template-columns 120px 672px (image beside text)
button opacity while the input is invalid: 0.4 → after typing: 1
The same card component chose its layout from the width of its container, not the window: that's what makes container queries better than media queries for reusable components. And :has() styled the button based on the state of a sibling inside the form, something that needed JavaScript before 2023.
Try it yourself
- Add
@layer reset, base, components, utilities;to a stylesheet and move your rules into layers. Then try to override a component style from an unlayered rule with the lowest specificity you can. - Make a flex row containing a long URL with no spaces. Watch it overflow; fix it with
min-width: 0andoverflow-wrap: anywhere. - Recreate experiment 5, then fix it three different ways without changing
#big'sz-index. - Build the menu page's cards with a container query instead of media queries, and put one card in a narrow sidebar.
Revision sheet: CSS
Key ideas
- The cascade sorts competing declarations by: origin and importance → context (shadow DOM) →
styleattribute → layers → specificity → order of appearance. Unlayered beats layered for normal declarations; the order reverses for!important. - Specificity is (ids, classes/attributes/pseudo-classes, types/pseudo-elements);
:is()/:not()/:has()take their most specific argument,:where()counts zero,*counts zero. - Inheritance: text properties inherit;
inherit,initial,unset,revertandrevert-layercontrol it explicitly. - Values go specified → computed → used → actual; custom properties are computed as tokens and substituted at
var()time;@propertygives them types (and makes them animatable). - Box model and
box-sizing; margin collapsing between blocks in normal flow; block formatting contexts (flow-root) contain floats and stop collapse. - Layout modes: normal flow, flexbox (one dimension; grow/shrink/basis,
min-width: auto), grid (two dimensions;fr,minmax,auto-fill/auto-fit, named areas, subgrid), positioning (relative, absolute against the nearest positioned ancestor, fixed, sticky). - Stacking contexts scope
z-index; created by positioned elements with a z-index, opacity < 1, transforms, filters,isolation: isolate, containment and more; the top layer sits above all of them. - Responsive: mobile-first
min-widthmedia queries, fluid units andclamp(), container queries for components, responsive images. - Modern CSS: nesting,
:has(), logical properties (margin-inline),oklch()andcolor-mix(), scroll-driven animations, view transitions,prefers-reduced-motion,prefers-color-scheme.
Numbers to remember
- 1rem = 16px by default; 1 CSS px ≈ 1/96 inch at arm's length.
- Specificity examples:
#a(1,0,0) >.a .b(0,2,0) >a.b(0,1,1) >a(0,0,1). - Typical mobile-first breakpoints: about 40rem (640px) and 64rem (1024px), but choose them from your content.
Pitfalls
- Fighting specificity with ids and
!importantinstead of layers or better structure. - Forgetting
box-sizing: border-box, ormin-width: 0on flex items with long content. - Expecting
z-indexto escape a parent's stacking context. height: 100vhon mobile (address bars); use100dvh/svh.- Styling with media queries when the component's container width is what matters.
- Removing focus outlines (
outline: none) without a visible replacement. - Animating layout properties (
top,width) instead oftransformandopacity(chapter 27).
Glossary
- Formatting context: the rules a box uses to lay out its children (block, inline, flex, grid).
- Containing block: the rectangle percentages and positioned offsets are measured against.
- Cascade layer: a named bucket (
@layer) with an explicit priority order. - Custom property: a
--namevalue that cascades and inherits, read withvar(). - Intrinsic size: the size content wants (
min-content,max-content,fit-content). - Logical properties: direction-relative properties (
inline/block,start/end) that adapt to writing modes.