Episode 1 — Fundamentals / 1.6 — CSS Core Fundamentals

1.6 — CSS Core Fundamentals: Quick Revision

Compact cheat sheet. Print-friendly.

How to use this material (instructions)

  1. Skim top-to-bottom in one pass before interviews or exams.
  2. If a row feels fuzzy — reopen the matching lesson: README.md1.6.a1.6.i.
  3. Drills1.6-Exercise-Questions.md.
  4. Polished answers1.6-Interview-Questions.md.

1.6.a CSS Syntax & Selectors

Rule anatomy

selector {
  property: value;   /* declaration */
}

Selector types

SelectorExampleSpecificity
Elementp { }0,0,0,1
Class.card { }0,0,1,0
ID#hero { }0,1,0,0
Universal* { }0,0,0,0
Attribute[type="email"] { }0,0,1,0
Groupingh1, h2, h3 { }Each selector scored independently

Combinators

CombinatorNameMeaning
(space)DescendantAny depth
>ChildDirect children only
+Adjacent siblingNext sibling
~General siblingAny following sibling

Key pseudo-classes

:hover · :focus · :focus-visible · :active · :first-child · :nth-child(n) · :not() · :is() · :has()

:has() — parent selector

.card:has(img) { padding: 0; }

Selects an element based on what it contains — inverts selector direction.

Pseudo-elements

::before · ::after · ::placeholder · ::selection


1.6.b Specificity & Cascade

Cascade priority (highest wins)

  1. Origin & importance (!important flips author/user/UA order)
  2. Inline stylesstyle="…" → specificity 1,0,0,0
  3. Layer order (@layer)
  4. Specificity — selector weight
  5. Source order — last wins (tie-breaker)

Specificity scoring

(inline, IDs, classes/attrs/pseudo-classes, elements/pseudo-elements)
SelectorScore
p0,0,0,1
.card0,0,1,0
#hero0,1,0,0
nav ul.menu li a:hover0,0,2,4

IDs beat any number of classes. Classes beat any number of elements.

Special selectors

SelectorSpecificity behavior
:is()Takes highest argument's specificity
:where()Zero specificity — ideal for defaults
:not()Takes argument's specificity
:has()Takes argument's specificity

!important

Jumps to top of origin tier. Avoid unless: a11y overrides, third-party containment, framework utilities.

@layer

Explicit cascade ordering for large codebases — later layers win.


1.6.c Inheritance & Computed Styles

Inherited by default

Typography: font-family, font-size, font-weight, line-height, color, text-align, letter-spacing, list-style, cursor, visibility

NOT inherited

Layout/Box: margin, padding, border, width, height, background, display, position, overflow, flex, grid

Keyword values

KeywordEffect
inheritForce parent's computed value
initialCSS spec default
unsetinherit if inheritable, initial if not
revertBrowser (user-agent) default

Computed value pipeline

Specified → Computed → Used → Actual (rendered)

Practical pattern

/* Set on root, inherit everywhere */
:root { font-family: system-ui, sans-serif; color: #1a1a2e; }

/* Fix form elements that break inheritance */
button, input, select, textarea { font: inherit; }

1.6.d Box Model

The four layers

┌──────── MARGIN ────────┐
│ ┌────── BORDER ──────┐ │
│ │ ┌──── PADDING ───┐ │ │
│ │ │    CONTENT     │ │ │
│ │ └────────────────┘ │ │
│ └────────────────────┘ │
└────────────────────────┘

box-sizing

Valuewidth includes
content-box (default)Content only (padding + border added on top)
border-boxContent + padding + border (total = declared width)

Always reset globally:

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

Margin collapsing

  • Vertical margins of adjacent block siblings collapse (larger wins).
  • Does not happen: horizontal margins, flex/grid children, BFC boundaries.

Margin auto

margin: 0 auto — horizontal centering for block elements.

Inline vs block

TypeWidthVertical margin/padding
BlockFull parent widthAffects layout
InlineContent widthDoes not push surrounding content
Inline-blockContent widthAffects layout

1.6.e CSS Units

Unit reference

UnitTypeRelative toBest for
pxAbsoluteScreen pixelBorders, shadows, thin lines
remRelative:root font-sizeTypography, spacing (scales with user pref)
emRelativeElement's own font-sizeComponent-internal spacing
%RelativeParent dimensionFluid widths
vw / vhRelativeViewport width/heightFull-screen sections
dvhRelativeDynamic viewport (mobile-safe)Mobile full-height
chRelativeWidth of 0 glyphLine width (max-width: 70ch)

rem vs em

remem
ReferenceRoot (stable)Element (local)
CompoundingNeverNested values multiply
Default choiceYesOnly for component-internal scaling

Accessibility

rem respects user font-size preferences; px does not. WCAG 1.4.4 requires text resizable to 200%.


1.6.f Modern CSS Functions

clamp(min, preferred, max)

font-size: clamp(1rem, 2.5vw, 2rem);
width: clamp(320px, 90%, 1200px);

Returns preferred, constrained between min and max.

min(a, b) — caps at maximum

width: min(100%, 400px);   /* never wider than 400px */

max(a, b) — enforces floor

width: max(250px, 25%);    /* at least 250px */

calc() — arithmetic with mixed units

width: calc(100% - 250px);

All functions accept mixed units (rem, vw, px, %).

Fluid typography

body { font-size: clamp(1rem, 0.875rem + 0.5vw, 1.25rem); }

Use rem bounds for accessibility.


1.6.g CSS Variables

Syntax

:root { --color-primary: #2563eb; }
.button { background: var(--color-primary); }
.fallback { color: var(--text, #333); }

Key properties

  • Inherit down the DOM tree.
  • Override at any scope (.dark-theme { --color-primary: #60a5fa; }).
  • JS-updatable: document.documentElement.style.setProperty('--x', val).
  • vs preprocessors: CSS vars are runtime; Sass vars are compile-time.

Theming pattern

:root { --bg: #fff; --text: #1a1a2e; }
[data-theme="dark"] { --bg: #0f172a; --text: #e2e8f0; }
body { background: var(--bg); color: var(--text); }

1.6.h Design Systems

Anatomy

LayerContains
PrinciplesBrand values, accessibility commitments
TokensColors, spacing, typography, radii, shadows
ComponentsButtons, cards, forms — with states, variants, a11y
DocumentationUsage guidelines, do/don't examples

Why systems matter

Prevents: 200 shades of gray, inconsistent spacing, specificity wars, brittle one-off styles.

Anti-patterns

  • Hardcoded values alongside tokens
  • No semantic layer (using --blue-500 in components directly)
  • Too many tokens (decision fatigue)

1.6.i Design Tokens

Three tiers

Primitive:   --blue-500: #2563eb        ← "this value exists"
Semantic:    --color-primary: --blue-500  ← "primary = this blue"
Component:   --button-bg: --color-primary ← "buttons use primary"

Token categories

Colors · Spacing · Typography · Border radius · Shadows · Breakpoints · Motion · Z-index

Spacing system (4px base)

TokenValueUse
--space-10.25rem (4px)Tiny gaps
--space-20.5rem (8px)Compact padding
--space-41rem (16px)Default spacing
--space-82rem (32px)Section spacing
--space-164rem (64px)Hero padding

Color contrast

  • 4.5:1 for normal text
  • 3:1 for large text (≥18pt or ≥14pt bold)

Platform distribution

tokens.json → CSS custom properties
            → Sass variables
            → iOS constants
            → Android resources
            → Tailwind config

One-liner definitions (25+ terms)

TermOne-liner
SelectorPattern that targets element(s) to style.
Declarationproperty: value; — what to change and to what.
SpecificityWeight that determines which competing rule wins.
CascadeAlgorithm resolving conflicts: origin → specificity → source order.
InheritanceChild inheriting a property value from its parent.
Computed valueFinal resolved value after cascade, inheritance, and unit resolution.
Box modelContent + padding + border + margin layers around every element.
border-boxbox-sizing where width includes content + padding + border.
Margin collapsingAdjacent vertical margins merge (larger wins, not additive).
remRelative unit based on root font-size — scales with user preference.
emRelative unit based on element's own font-size — compounds when nested.
vw / vh1% of viewport width / height.
dvhDynamic viewport height — adjusts for mobile address bar.
chWidth of the 0 glyph — useful for line width constraints.
clamp()clamp(min, preferred, max) — fluid value with bounds.
min()Returns the smallest of its arguments (caps at max).
max()Returns the largest of its arguments (enforces floor).
calc()Arithmetic with mixed CSS units.
Custom property--name variable defined in CSS, consumed via var(--name).
:rootPseudo-class targeting <html> — common home for global variables.
:has()Parent selector — selects elements based on their descendants.
:where()Selector list with zero specificity — ideal for overridable defaults.
@layerCascade layer — explicit ordering of style priority.
Design systemShared vocabulary of constraints, tokens, components, and docs.
Design tokenNamed, platform-agnostic design decision (color, spacing, etc.).
Primitive tokenRaw palette value (--blue-500).
Semantic tokenRole-based mapping (--color-primary).
Component tokenScoped binding (--button-bg).

Master workflow — CSS fundamentals stack

  1. Selectors target elements → cascade determines which rule wins.
  2. Specificity scores: inline > ID > class > element.
  3. Inheritance flows typography down the tree; box properties don't inherit.
  4. Box model (border-box) governs element sizing: content + padding + border.
  5. Units (rem, em, %, vw) make layouts scale with user preferences and viewports.
  6. CSS functions (clamp, min, max) enable fluid responsive design.
  7. Custom properties (--var) centralize values; enable theming and runtime updates.
  8. Design systems constrain choices to tokens → consistency across the product.
  9. Design tokens (primitive → semantic → component) are the single source of truth.
  10. All layers connect: tokens → custom properties → components → cascade → pixels.

End of 1.6 quick revision.