Modern HTML & CSS
HTML & CSS Moderno Cheatsheet
Quick-reference cards for semantic HTML5 landmarks, accessibility rules, Cascade Layers, Flexbox, Grid/Subgrid, Container Queries, reduced motion, and RTL logical properties. Print to PDF cleanly with Ctrl/Cmd + P.
Save or print this cheatsheet as PDF
Print-ready layout: open in one click and save as PDF from your browser, no account or email required.
Production Safety Checklist
Verify these six invariants on every new page or component before shipping.
- Apply *, *::before, *::after { box-sizing: border-box; } so padding and borders never expand declared widths unexpectedly.
- Include exactly one visible <main> landmark, a single primary <h1>, and never skip heading levels (h1 -> h3 hurts screen reader navigation).
- Use <button type="button"> for actions and <a href="..."> for navigation; never attach click handlers to clickable <div> elements.
- Give every <img> an alt attribute (descriptive text or alt="" for decorative graphics) and connect every form control to a visible <label for="...">.
- Prefer overflow: clip (not overflow: hidden) on rounded ancestors of position: sticky headers, and isolate overlays with isolation: isolate.
- Use CSS Logical Properties (margin-inline, padding-block, border-inline-start) instead of left/right physical properties so RTL scripts mirror automatically.
Semantic HTML5 Landmarks
Document Landmark Skeleton
<header> <a href="/">Brand</a> <nav aria-label="Main navigation">...</nav> </header> <main id="content"> <h1>Article Title</h1> <article> <figure> <img src="/chart.png" alt="Quarterly traffic growth chart" /> <figcaption>Q1–Q4 organic visits.</figcaption> </figure> <time datetime="2026-05-12">May 12, 2026</time> </article> </main> <footer>...</footer>Top-level landmarks allow assistive technology users to jump straight to navigation, main content, or the footer.
Watch out: Putting navigation links inside <main> or using multiple <main> landmarks without hidden attributes confuses landmark menus.
Native Actions vs Navigation Links
<a class="btn" href="/pricing/">Compare plans</a> <button type="button" class="btn">Save changes</button>Links change URL or focus destination; buttons trigger state updates, modals, or form submissions.
Watch out: An <a> tag without an href loses keyboard focusability and Enter activation; a <button> inside a <form> defaults to type="submit" unless type="button" is specified.
Forms, Focus & Accessibility
Accessible Form Control & Error Hint
<label for="user-email">Work email</label> <input id="user-email" name="email" type="email" required aria-describedby="email-hint" /> <p id="email-hint">We never share your address.</p>Matching for="user-email" and id="user-email" announces the label and enlarges the clickable hit area.
Watch out: Relying solely on placeholder text as a label disappears as soon as the user starts typing and fails WCAG 2.1.
Keyboard Focus Ring (:focus-visible)
:focus-visible { outline: 3px solid #0369a1; outline-offset: 2px; }:focus-visible displays high-contrast outlines for keyboard navigation without noisy rings on mouse clicks.
Watch out: Never write outline: none without replacing it with an equally visible focus indicator.
Specificity & Cascade Precedence
Higher rows lose to lower rows only when their Cascade Layer or !important priority also yields.
| Selector / Feature | Weight (a,b,c) | Notes |
|---|---|---|
| * and :where(.card) | (0, 0, 0) | Zero specificity — ideal for low-conflict resets |
| p, h1, main::before | (0, 0, 1) / (0, 0, 2) | Type selectors and ::pseudo-elements |
| .btn, [type="email"], :hover, :is(.a) | (0, 1, 0) | Classes, attributes, pseudo-classes (:is takes highest arg) |
| #header-nav | (1, 0, 0) | ID selector outweighs any number of classes |
| @layer components { #id { ... } } | Layered < Unlayered | Any unlayered rule beats every @layer rule regardless of IDs |
| style="..." (inline attribute) | Beats author rules | Only overridden by author/user-agent !important |
Cascade Layers, Tokens & :has()
Ordered @layer Architecture
@layer reset, base, components, utilities; @layer base { :where(h1, h2, p) { margin: 0; } } @layer components { .btn { background-color: var(--accent, #0369a1); color: #ffffff; } }Declaring the layer order once at the top of the stylesheet locks precedence independently of import order.
Watch out: An unlayered rule placed outside @layer always overrides styles inside @layer, which can surprise teams mixing legacy stylesheets.
Parent Selection with :has()
.card:has(input[type="checkbox"]:checked) { border-color: #0369a1; background-color: #f0f9ff; }:has() inspects descendants or following siblings cleanly in pure CSS with zero JavaScript event listeners.
Watch out: Keep :has() scoped to component containers rather than matching broad body:has(*) trees cleanly.
Box Model, Clamp & Units
Global Border-Box & Reading Measure
*, *::before, *::after { box-sizing: border-box; } .prose { width: min(100% - 2rem, 65ch); margin-inline: auto; }min(100% - 2rem, 65ch) creates an elastic container with side gutters and a comfortable 65-character reading column.
Watch out: Using fixed px widths without min() causes horizontal overflow on 375px mobile screens.
Fluid Typography via clamp()
h1 { font-size: clamp(1.5rem, 1.1rem + 2vw, 2.5rem); line-height: 1.15; }Combine a rem offset with vw inside the preferred argument so browser zoom (Ctrl +) still scales headings smoothly.
Watch out: Using pure vw (e.g. font-size: 4vw) disables text resizing on browser zoom and violates WCAG 1.4.4.
Flexbox Layout Patterns
Responsive Wrapping Toolbar
.toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 0.75rem 1.25rem; } .toolbar-cta { margin-inline-start: auto; }flex-wrap: wrap lets items drop cleanly onto a second line on narrow viewports while margin-inline-start: auto pushes the CTA.
Watch out: Leaving flex-wrap: nowrap on navigation rows forces items to shrink past min-content or overflow horizontally.
Equal-Basis Wrapping Cards
.pill-row { display: flex; flex-wrap: wrap; gap: 1rem; } .pill-row > * { flex: 1 1 14rem; min-width: 0; }min-width: 0 prevents long words, code blocks, or nested flex children from refusing to shrink below their intrinsic width.
Watch out: Forgetting min-width: 0 is the #1 cause of broken text truncation (text-overflow: ellipsis) inside flex items.
CSS Grid & Subgrid
Intrinsic Auto-Fit Responsive Grid
.card-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 240px), 1fr)); gap: 1.25rem; }minmax(min(100%, 240px), 1fr) guarantees cards never overflow even if the container is narrower than 240px.
Watch out: Using repeat(auto-fill, minmax(240px, 1fr)) leaves empty phantom tracks on the right when fewer items exist.
Cross-Card Row Alignment with Subgrid
.plan-card { display: grid; grid-row: span 3; grid-template-rows: subgrid; gap: 0.75rem; }Subgrid shares the parent row tracks so card headings, body copy, and footer buttons line up across siblings.
Watch out: The child item must span the exact number of subgrid rows (grid-row: span 3) or rows collapse into one track.
Sticky, Stacking & @container
Safe Sticky Header & Isolated Layers
.card-shell { overflow-x: clip; isolation: isolate; } .sticky-header { position: sticky; inset-block-start: 0; z-index: 10; }overflow: clip masks overflowing decoration without creating a scroll container, preserving sticky ancestry.
Watch out: Any ancestor with overflow: hidden/auto/scroll traps position: sticky; opacity < 1 or transform creates a new stacking context.
Component-Aware @container Query
.slot { container-type: inline-size; container-name: card; } @container card (min-width: 380px) { .media-card { grid-template-columns: 120px 1fr; } }Components adapt to the slot they inhabit (sidebar vs main area) independently of browser window breakpoints.
Watch out: Querying width inside the container element itself fails cleanly—the selector rule must target a descendant of the container.
Compositor Motion & RTL Logical CSS
GPU Motion + Reduced Motion Guard
.card { transition: transform 200ms ease, opacity 200ms ease; } @media (prefers-reduced-motion: reduce) { .card { transition: none; } }Animating transform and opacity runs on the compositor thread without triggering expensive Layout or Paint steps.
Watch out: Transitioning width, height, top, or left forces full page layout recalculation every frame.
Direction-Agnostic Blockquote Callout
.callout { margin-inline-start: 0; padding-block: 0.875rem; padding-inline-start: 1.25rem; border-inline-start: 4px solid #0369a1; border-start-end-radius: 0.5rem; }In LTR inline-start is left; in RTL (dir="rtl") it automatically resolves to the right edge with zero duplicated CSS.
Watch out: Mixing margin-left with padding-inline-end creates asymmetric spacing whenever text direction reverses.
Top Layer, <dialog> & Popover API
Zero-JS Popover Trigger + Target
<button type="button" popovertarget="hint-box">Quick Info</button> <div id="hint-box" popover="auto"> Auto-dismissed on Escape or outside click. </div>Top Layer popovers paint above every stacking context without managing high z-index scales or outside-click listeners.
Watch out: Always trigger popovers from a native <button type="button"> — static <div> triggers cannot be reached by keyboard Tab.
<dialog> Backdrop & @starting-style
dialog::backdrop { background-color: rgba(15, 23, 42, 0.55); } dialog[open] { opacity: 1; transition: opacity 200ms ease, display 200ms allow-discrete; } @starting-style { dialog[open] { opacity: 0; } }@starting-style lets newly shown top-layer elements animate smoothly from an initial opacity frame without JavaScript.
Watch out: Without transition-behavior: allow-discrete on display/overlay, exit animations snap shut before easing completes.
Cascade Isolation (@layer vs @scope)
Donut Scoping With @scope Root and Limit
@scope (.card) to (.nested-slot) { h2 { color: #0369a1; } p { margin-block: 0.5rem; } }@scope restricts selectors to a subtree bounded between a root (.card) and an optional exclusion boundary (.nested-slot).
Watch out: Descendant selectors like .card p leak into embedded child widgets unless blocked with a donut limit to (...).
Layer Ordering vs Scope Boundaries
@layer reset, base, components, utilities; @layer base { :where(h1, h2, p) { margin: 0; } }Use @layer to control broad stylesheet precedence globally, and combine @scope to keep component DOM trees self-contained.
Watch out: Any CSS outside all @layer declarations always beats layered styles regardless of selector specificity.
Scroll Snap, Print & Adaptive Modes
Horizontal Scroll Snap Rail
.rail { display: flex; gap: 1rem; overflow-x: auto; scroll-snap-type: x mandatory; scroll-padding-inline: 1rem; } .slide { flex: 0 0 260px; scroll-snap-align: start; }Provides crisp momentum card snapping on touchscreens and trackpads with zero carousel JavaScript.
Watch out: Forgetting scroll-padding-inline hides the card edge flush against container padding when snapping to start.
Forced Colors (High Contrast) & Print Stylesheet
@media (forced-colors: active) { .btn { border: 2px solid CanvasText; } } @media print { nav, .no-print { display: none; } }Explicit 2px CanvasText borders keep button boundaries unmistakable when OS High Contrast overrides background fills.
Watch out: Relying only on box-shadow or background tint for card boundaries makes controls invisible in forced-colors or black-and-white print.