Episode 1 — Fundamentals / 1.5 — Semantic HTML and Browser Rendering

1.5 — Semantic HTML & Browser Rendering: 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.5.a1.5.i.
  3. Drills1.5-Exercise-Questions.md.
  4. Polished answers1.5-Interview-Questions.md.

1.5.a Browser Rendering Pipeline

The Critical Rendering Path

HTML bytes ──► DOM Tree ──┐
                          ├──► Render Tree ──► Layout ──► Paint ──► Composite
CSS  bytes ──► CSSOM Tree ┘                                            │
                                                                       ▼
                                                                 Pixels on screen

Seven Stages

StageWhat happens
Download & DecodeHTML streamed from server; CSS/JS discovered and fetched.
Parse HTML → DOMToken → tree of element/text nodes (invalid markup auto-repaired).
Parse CSS → CSSOMSelectors, cascade, inheritance → style rules tree.
Render TreeDOM + CSSOM combined; display: none excluded; pseudo-elements added.
Layout (Reflow)Geometry computed: positions, sizes, line breaks, scrollable overflow.
PaintPixels filled: text, colors, borders, shadows, images.
CompositeLayers assembled (GPU); transform/opacity changes can skip layout + paint.

Blocking Resources

  • CSS is render-blocking — browser won't paint until CSSOM is built.
  • JS (without async/defer) is parser-blocking — HTML parsing halts while script downloads and executes.
  • defer: download in parallel, execute after HTML parsing.
  • async: download in parallel, execute immediately (order not guaranteed).

1.5.b Reflow & Repaint

Vocabulary

TermAlso calledWhat changed?
ReflowLayoutGeometry — positions, sizes, line breaks
RepaintPaintVisuals — colors, shadows, text rasterization (same geometry)
RecompositeComposite onlyLayer stack — often transform / opacity on promoted layers

Common Reflow Triggers

  • Changing width, height, border, fonts, padding, margin
  • DOM insert/remove that shifts siblings
  • Window resize, font load swaps
  • Reading layout (offsetHeight, getBoundingClientRect()) after writing styles

Layout Thrashing

Bad: write style → read geometry → write → read (loop forces sync layout each iteration). Fix: batch all reads first, then batch writes; or use requestAnimationFrame.

CLS (Cumulative Layout Shift)

CauseFix
Images/iframes without dimensionsAdd width/height or aspect-ratio
Late-loading web fonts (FOIT/FOUT)font-display strategy; preload critical fonts
Dynamically injected banners/adsReserve space; insert below viewport
Content inserted above existing UISkeleton placeholders; fixed-height containers

1.5.c Semantic Landmark Tags

Core Landmarks

ElementRoleNotes
<header>BannerIntro content for nearest sectioning ancestor or page
<nav>NavigationMajor navigation blocks; multiple OK — distinguish with aria-label
<main>MainOne per document; primary content area
<aside>ComplementarySidebars, related links, pull quotes
<footer>Content InfoLegal, meta links, copyright

section vs article

ElementMental modelExample
<section>Thematic grouping with a heading"Features" chapter on a landing page
<article>Self-contained compositionBlog post, product card, comment

Document Sketch

<body>
  <header>… branding …</header>
  <nav aria-label="Primary"></nav>
  <main>
    <h1>Page title</h1>
    <section aria-labelledby="feat-heading">
      <h2 id="feat-heading">Features</h2>
      <article>…feature card…</article>
    </section>
  </main>
  <aside>… related …</aside>
  <footer>… legal …</footer>
</body>

Anti-pattern: wrapping every widget in <article> "for SEO" — use meaning, not superstition.


1.5.d SEO & Semantic HTML

HTML Signals That Still Matter

SignalWhy
<title>Primary label in search results / tabs; strong relevance cue
Meta descriptionNot a direct ranking factor everywhere — influences snippet CTR
Heading hierarchyCommunicates topical structure to crawlers and users
Canonical link<link rel="canonical" href="…"> — consolidates duplicate URLs
Semantic landmarksHelps parsers distinguish boilerplate from primary content
Internal linkingDistributes page authority; helps crawlers discover content

SEO Anti-Patterns

  • Keyword stuffing in hidden text or repetitive headings
  • Cloaking — different content for bots vs users (policy violation)
  • Fake headings<h2> styled as body text for tiny promo lines
  • Link farms and misleading rel usage — trust damage

Structured Data (JSON-LD)

<script type="application/ld+json"> describes entities (Article, Product, FAQ). Rich results not guaranteed; incorrect markup can cause manual actions. Treat as precision labeling, not SEO spray paint.


1.5.e Accessibility & ARIA

Inclusive Design Spectrum

Disability typePermanentTemporarySituational
MotorLimb differenceBroken armHolding baby
VisionBlindEye surgeryBright sunlight
AuditoryDeafEar infectionNoisy environment
CognitiveLearning disabilityConcussionDistraction

Native HTML First

NeedPreferAvoid
Button<button><div onclick> + role="button"
Link<a href><span tabindex="0"> faking links
Text field<input> / <textarea>contenteditable for forms
Checkbox<input type="checkbox">Custom div toggles without semantics
Expandable<details> / <summary>Hand-rolled unless native cannot meet requirements

ARIA in Three Buckets

BucketExamples
Rolesrole="navigation", role="dialog" — do not duplicate native roles
Statesaria-expanded, aria-selected, aria-checked — live state
Propertiesaria-labelledby, aria-describedby, aria-live — relationships

The First Rule of ARIA

If you can use a native HTML element with the needed semantics and behavior, do.

Second rule: do not change native semantics unless you know why.

Keyboard Basics

KeyAction
Tab / Shift+TabMove focus between focusable elements
EnterActivate buttons and links
SpaceToggle buttons/checkboxes
EscapeClose dialogs (if implemented)

Never remove outline without providing equally clear replacement focus styles.

Testing Workflow

  1. Keyboard-only — complete tasks without a mouse.
  2. Zoom 200% — does layout break?
  3. Screen reader smoke test (VoiceOver / NVDA): landmarks, headings, labels.
  4. Automated: axe DevTools / Lighthouse accessibility.
  5. Color contrast check (WCAG 4.5:1 for normal text).

1.5.f Headings Hierarchy

The Outline Model

h1  Page topic
├─ h2  Major section
│  ├─ h3  Subtopic
│  └─ h3  Subtopic
└─ h2  Major section
   └─ h3  Subtopic

Rules

  • Do not skip levels (h1h4 breaks mental model).
  • h1 = primary purpose of the page/view.
  • Headings are not font sizes — use CSS for appearance.
  • Pair <section> with a heading (aria-labelledby).
  • <title>h1: <title> is for tab/snippet; h1 is on-page topic.

Anti-Patterns

Anti-patternWhy it hurts
Skipping levels (h1h4)Users lose mental model of depth
Heading for visual linePollutes outline; spam for SR users
Every widget at h2 levelRotor becomes noisy; no hierarchy

1.5.g Lists

ul vs ol vs dl

ElementMeaningUse when
<ul>Unordered groupSequence does not matter (features, nav links)
<ol>Ordered groupSequence matters (steps, rankings, legal clauses)
<dl>Description listTerm–definition pairs (glossary, metadata)

Useful ol Attributes

AttributeEffect
startBegin counting at a given number
reversedDescending order (countdowns, top-N)
typePresentation hint (1, a, A, i, I)

Navigation Lists

Nav link groups are commonly ul > li > a — CSS hides bullets, but list semantics are preserved (screen readers announce count and position).


1.5.h Responsive Images

Two Tools, Two Jobs

ToolJob
srcset + sizesPick the right resolution file
<picture> + <source>Pick the right format or art direction crop

srcset Descriptors

DescriptorMeaningExample
wIntrinsic width in pixelshero-400.jpg 400w
xDevice pixel ratioicon@2x.png 2x

Modern Formats

FormatTrade-off
WebPBroad support; good compression vs JPEG/PNG
AVIFOften smaller; higher encode cost; provide fallback

Optimization Checklist

  • width/height or aspect-ratio on <img> → prevents CLS.
  • loading="lazy" for below-fold images (do not lazy-load the LCP hero).
  • fetchpriority="high" on LCP image (sparingly).
  • SVG for logos/icons — scales without resolution variants.
  • Always keep a fallback <img src> for unknown clients.

1.5.i Links & Forms

Internal vs External Links

TypePatternNotes
Internal<a href="/pricing">Root-relative preferred
External<a href="https://other.example">Absolute URL
New tabtarget="_blank"Always add rel="noopener" (+ noreferrer per policy)

Important rel Values

relPurpose
noopenerPrevent window.opener access (security)
noreferrerStrip Referer header + implies noopener
nofollowHint: do not pass ranking credit
sponsoredPaid/partner links
ugcUser-generated content links

Form Anatomy

<form action="/subscribe" method="post">
  <label for="email">Email</label>
  <input id="email" name="email" type="email" autocomplete="email" required />
  <button type="submit">Subscribe</button>
</form>
  • label forid — accessible name + bigger click target.
  • name — what the server receives in the payload.
  • fieldset/legend — groups related controls (radio groups, address blocks).

Common Input Types

typeBuilt-in behavior
emailEmail validation hint + keyboard
urlURL pattern hint
numberSteppers; beware empty vs 0
telPhone keyboard on mobile
date / timeNative date pickers
searchSearch field semantics
checkbox / radioSelection controls; radios share name

HTML5 Validation Attributes

required · pattern · min/max · minlength/maxlength · step

Client vs Server Validation

LayerRoleTrust
HTML5 / JSFast UX feedback, fewer round tripsUntrusted — user can bypass
ServerAuthoritative rules, authz, DB invariantsSource of truth

Never rely on client validation for security. Server validates truth.


One-liner definitions (25+ terms)

TermOne-liner
DOMTree representation of HTML elements used by browsers to render pages.
CSSOMTree representation of CSS styles paired with the DOM for styling.
Render treeCombined DOM + CSSOM — only visible elements that need painting.
Layout / ReflowEngine computes geometry: positions, sizes, line breaks for every box.
PaintFilling pixels: text, colors, borders, shadows, images.
CompositeAssembling painted layers (GPU) into the final frame.
CRPCritical Rendering Path — minimum work to first meaningful pixels.
CLSCumulative Layout Shift — metric for unexpected visual movement.
LCPLargest Contentful Paint — when the biggest visible element renders.
FCPFirst Contentful Paint — when the first bit of UI appears.
ReflowRe-computation of layout geometry (expensive).
RepaintRedraw of visual appearance without geometry change.
Layout thrashingWrite→read geometry interleaving that forces synchronous layout.
LandmarkHTML element exposing a named region to assistive tech (nav, main, etc.).
ARIAAccessible Rich Internet Applications — roles/states/properties for the a11y tree.
Accessible nameThe label assistive tech announces for an element (from label, aria-label, etc.).
Screen readerSoftware that reads UI content aloud (VoiceOver, NVDA, JAWS).
WCAGWeb Content Accessibility Guidelines — international a11y standard.
Semantic HTMLUsing elements for their meaning, not their default appearance.
srcsetAttribute listing image candidates with width or DPR descriptors.
sizesAttribute telling the browser how wide the image renders at breakpoints.
Art directionServing different image crops/compositions at different breakpoints.
WebP / AVIFModern image formats with better compression than JPEG/PNG.
Canonical URL<link rel="canonical"> — tells search engines the preferred URL for a page.
JSON-LDStructured data format embedded in <script> for rich search results.
noopenerrel value preventing opened tab from accessing window.opener.
CSRFCross-Site Request Forgery — server-side tokens prevent forged form submissions.

Master workflow — The Rendering & Semantics Stack

  1. HTML bytes arrive from server → parsed into DOM tree.
  2. CSS bytes arrive → parsed into CSSOM tree.
  3. DOM + CSSOM → Render tree (visible elements only).
  4. Layout: engine computes geometry for every box.
  5. Paint: pixels filled — text, borders, colors, images.
  6. Composite: GPU layers assembled → frame displayed.
  7. Semantic tags (main, nav, header) make the DOM meaningful for a11y tools + search engines.
  8. ARIA bridges gaps when native HTML cannot express roles/states.
  9. Responsive images (srcset/sizes/<picture>) deliver right-sized assets.
  10. Forms connect user input to server-side truth — client validation is UX, server is authority.

End of 1.5 quick revision.