Skip to content

Keep your coding agent up to date with the latest web best practices

Release v0.0.97

github-actions[bot]7de37f16843b
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index 501ecf5..7675145 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -8,7 +8,7 @@
"name": "modern-web-guidance",
"source": "./",
"description": "Google Chrome's agent skills collection",
- "version": "0.0.96"
+ "version": "0.0.97"
}
]
}
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 72b2666..b078571 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "modern-web-guidance",
"description": "Google Chrome's agent skills collection",
- "version": "0.0.96",
+ "version": "0.0.97",
"author": {
"name": "Google Chrome"
}
diff --git a/README.md b/README.md
index 62f602b..a85c14f 100644
--- a/README.md
+++ b/README.md
@@ -2,7 +2,7 @@
This curated collection of skills, tools, and AI-ready documentation injects Chrome's web platform knowledge directly into your workflow, ensuring your coding agent builds apps that are modern, fast, and secure by default.
-#### Skill Coverage in `v0.0.96`
+#### Skill Coverage in `v0.0.97`
<details>
<summary><strong>83 web features with implementation guidance from Chrome's experts</strong>: `::backdrop`, `:autofill`, `:has()`, `:not()`, `:user-valid and :user-invalid`, `@starting-style`, `&lt;details>`, `&lt;dialog closedby>`, `&lt;dialog>`, `&lt;link rel="expect">`, `&lt;link rel="preload">`, `AbortController and AbortSignal`, `accent-color`, `Active view transition`, `Anchor position container queries`, `Anchor positioning`, `blocking="render"`, `calc-size()`, `color-scheme`, `Container queries`, `Container scroll-state queries`, `content-visibility`, `Cross-document view transitions`, `Customizable &lt;select>`, `Email, telephone, and URL &lt;input> types`, `enterkeyhint`, `Event timing`, `Fetch`, `Fetch priority`, `fetchLater`, `field-sizing`, `font-size-adjust`, `Form-associated WebMCP attributes`, `hidden="until-found"`, `image-set()`, `Individual transform properties`, `inert`, `inputmode`, `Interest invokers`, `interpolate-size`, `Intersection observer`, `Intl.DurationFormat`, `Invoker commands`, `Language detector`, `light-dark()`, `linear() easing`, `Long animation frames`, `Masks`, `moveBefore()`, `Mutually exclusive &lt;details> elements`, `Navigation API`, `navigator.modelContext`, `overlay`, `Page visibility`, `Page visibility state`, `Popover`, `popover="hint"`, `prefers-color-scheme media query`, `prefers-contrast media query`, `prefers-reduced-motion media query`, `Registered custom properties`, `Scheduler API`, `Scroll snap`, `Scroll-driven animations`, `scroll-initial-target`, `scrollbar-color`, `scrollbar-width`, `scrollend`, `scrollIntoView()`, `sibling-count() and sibling-index()`, `sin(), cos(), tan(), asin(), acos(), atan(), and atan2() (CSS)`, `Speculation rules`, `Summarizer`, `Temporal`, `text-box`, `text-wrap`, `text-wrap: balance`, `text-wrap: pretty`, `Top-level await`, `transition-behavior`, `Translator`, `View transitions`, `view-transition-class`</summary>
diff --git a/gemini-extension.json b/gemini-extension.json
index ec93dfb..6ad0e75 100644
--- a/gemini-extension.json
+++ b/gemini-extension.json
@@ -1,7 +1,7 @@
{
"name": "modern-web-guidance",
"description": "Google Chrome's web development agent skills.",
- "version": "0.0.96",
+ "version": "0.0.97",
"author": {
"name": "Google Chrome"
}
diff --git a/package.json b/package.json
index fadb553..d68bc9c 100644
--- a/package.json
+++ b/package.json
@@ -2,7 +2,7 @@
"name": "modern-web-guidance",
"displayName": "Modern Web Guidance",
"description": "Curated collection of agent skills for modern web development.",
- "version": "0.0.96",
+ "version": "0.0.97",
"publisher": "GoogleChrome",
"engines": {
"vscode": "^1.90.0",
diff --git a/skills/css/SKILL.md b/skills/css/SKILL.md
index 6cba910..a2f3e9e 100644
--- a/skills/css/SKILL.md
+++ b/skills/css/SKILL.md
@@ -7,183 +7,450 @@ description: Action-oriented guidelines for modern CSS architecture, layouts, an
These guidelines provide a high-density reference for writing maintainable, performant, and standard-compliant CSS.
-## 1. Architectural Foundations and The Cascade
-Effective CSS architecture focuses on managing the global namespace and controlling specificity natively.
-
-### DOs and DON'Ts
-- **DO** use a global `box-sizing: border-box` reset to ensure padding doesn't break layouts.
-- **DO** use keywords like `inherit`, `initial`, `unset`, or `revert` to explicitly control inheritance.
-- **DO** use **Cascade Layers** (`@layer`) to define explicit priority zones (e.g., `reset`, `base`, `theme`, `components`, `utilities`).
-- **DO** declare the layer order upfront in your main CSS file: `@layer reset, base, theme, components, utilities;`.
-- **DO** understand that `!important` declarations in a lower-priority layer override those in a higher-priority layer (precedence is reversed).
-- **DO** use specialized naming conventions like **BEM** (`.block__element--modifier`) to avoid namespace collisions.
-- **DO** use `isolation: isolate` to create a fresh stacking context without side-effects.
-
-### Code Example: Foundations & Reset
+1. [1. Foundations](#1-foundations)
+2. [2. Inheritance and The Cascade](#2-inheritance-and-the-cascade)
+3. [3. Selectors and scoping](#3-selectors-and-scoping)
+ 1. [Prefer CSS selectors over JS for complex element targeting](#prefer-css-selectors-over-js-for-complex-element-targeting)
+ 2. [Use `:is()` (or `:where()`) instead of CSS rule duplication for fallbacks](#use-is-or-where-instead-of-css-rule-duplication-for-fallbacks)
+ 3. [Avoid overmatching](#avoid-overmatching)
+ 4. [Nesting and scoping](#nesting-and-scoping)
+4. [4. Interactivity](#4-interactivity)
+ 1. [Focus management](#focus-management)
+ 2. [Touch targets](#touch-targets)
+5. [5. Design Tokens and Theming](#5-design-tokens-and-theming)
+ 1. [Dark mode](#dark-mode)
+ 2. [Forced Colors Mode](#forced-colors-mode)
+ 3. [Generating tints](#generating-tints)
+ 4. [Theming browser-generated UI](#theming-browser-generated-ui)
+6. [6. Responsive design](#6-responsive-design)
+ 1. [Responsive Typography](#responsive-typography)
+7. [7. Typography](#7-typography)
+ 1. [Text wrapping](#text-wrapping)
+8. [8. Visual effects](#8-visual-effects)
+ 1. [Depth and texture](#depth-and-texture)
+ 2. [Shapes](#shapes)
+ 3. [Gradients and `color-mix()`](#gradients-and-color-mix)
+ 4. [Patterns](#patterns)
+9. [9. Transitions \& animations](#9-transitions--animations)
+ 1. [Performance](#performance)
+ 2. [Accessibility](#accessibility)
+10. [10. Generated content](#10-generated-content)
+
+
+## 1. Foundations
+
+Be allergic to knowledge duplication. Prefer variables over repetition, but whenever possible, prefer built-in conventions such as:
+- `currentColor` instead of defining a variable and setting `color` to it
+- The `inherit` keyword instead of defining a variable on the parent and using it on the same property across parent and child.
+- `em` units instead of `font-size: var(--size)`
+- `cqw`/`cqh` (or their logical versions — `cqi`/`cqb`) units instead of repeating box model values.
+- Code duplication is not knowledge duplication. The goal is robustness and maintainability, not saving characters.
+- Prefer **logical properties and values** over physical ones (e.g. `margin-inline-start` instead of `margin-left`) so that styles adapt to different writing modes and orientations. Even if the page author does not plan to localize, external translation tools often display translated text in context.
+- Do not use logical properties indiscriminately — ask yourself "would I want this to flip in RTL?" — if the answer is no, use the physical property instead.
+- Consider different viewing modes (dark mode, high contrast mode), different viewport sizes, and different input modes (touch, keyboard, pointer).
+
+## 2. Inheritance and The Cascade
+
+**Avoid** introducing BEM naming conventions to manage specificity.
+Instead, use modern CSS features such as cascade layers and `:where()` to make cascade behavior predictable and follow author intent.
+
+Use cascade layers (`@layer`) to define explicit priority zones (e.g., `reset`, `base`, `theme`, `components`, `utilities`), and declare their order upfront (e.g. `@layer reset, base, theme, components, utilities;`).
+Within each layer, use `:where()` to make selectors only compete based on meaningful signals, not incidental filters (`:not()` edge cases, remote ancestors, etc.) or for one-off easily overridable defaults.
+
+Use keywords like `inherit`, `initial`, `unset`, or `revert` instead of explicit values to improve maintainability and better express intent.
+Examples:
+- When specifying a transition on a child that should match the parent's `transition-*` properties, instead of repeating the transition properties on the child, use `transition: inherit` (reduce duplication, improve maintainability)
+- Use `initial` to reset a property to its initial value instead of specifying the value explicitly (clearer expression of intent)
+
+## 3. Selectors and scoping
+
+Modern browser-native selectors reduce the need for preprocessors and complex state-tracking in JS.
+
+### Prefer CSS selectors over JS for complex element targeting
+
+- **DO** use `:has()` to style parents based on child state instead of managing classes in JS (e.g. `label:has(:checked)` instead of a manual `label.has-checked` class) For more information, see the guides at `child-state-based-styling` (via `npx -p modern-web-guidance@latest -- modern-web retrieve "child-state-based-styling"`) and `content-based-styling` (via `npx -p modern-web-guidance@latest -- modern-web retrieve "content-based-styling"`).
+- **DO NOT** nest `:has()` or use pseudo-elements inside it (browser API limitation)
+- Use `:nth-child(<An+B> of <selector>)` when you need to style every n-th element of a certain type. E.g. `details:nth-child(1 of [open])` will style the first open `<details>` element it finds, whereas `details[open]:first-child` would style only the first child if and only if it was open.
+
+### Use `:is()` (or `:where()`) instead of CSS rule duplication for fallbacks
+
+**DO NOT** duplicate CSS rules to provide fallbacks for pseudo-classes that may not be supported — use `:is()` or `:where()` instead and take advantage of their forgiving parsing rules.
+
```css
-/* Global Reset */
-*, *::before, *::after {
- box-sizing: border-box;
+/* BAD: duplicate rules instead of using `:where()` */
+[popover]:popover-open {
+ /* styles for native popovers */
+}
+[popover].\:popover-open {
+ /* same styles again, for polyfilled popovers */
}
-/* 1. Define order */
-@layer reset, theme, components;
+/* GOOD */
+[popover]:where(:popover-open, .\:popover-open) {
+ /* same styles in one rule */
+}
+```
-/* 2. Low priority foundational styles */
-@layer reset {
- a { color: inherit; text-decoration: none; }
+Do NOT use this for pseudo-elements, as they are not supported in `:is()` or `:where()`.
+
+### Avoid overmatching
+
+Write selectors in a way that expresses _intent_.
+
+#### Use `:not()` instead of overrides to exclude irrelevant states/targets
+
+When the intent is to exclude certain states or elements that are fundamentally irrelevant, use `:not()`.
+
+For example, to apply bottom borders between list items, don't do this:
+
+```css
+.fancy-list li {
+ border-bottom: 1px solid silver;
}
-/* 3. Higher priority component styles */
-@layer components {
- .btn {
- background: var(--brand);
- color: white;
- }
+.fancy-list li:last-child {
+ border-bottom: none;
}
+```
-/* Unlayered styles (Highest priority outside of !important) */
-.emergency-override {
- display: block;
+This can unintentionally overwrite a desirable `border-bottom` set from another rule.
+The actual intent was to only apply the bottom border to the non-last `li`s. The code above is a workaround that poorly expresses this intent. Instead, this expresses intent more clearly:
+
+```css
+.fancy-list li:not(:last-child) {
+ border-bottom: 1px solid silver;
}
```
-## 2. Advanced Visuals, Borders, and Blend Modes
-Modern CSS provides advanced effects for depth, textures, and non-rectangular geometries.
+Similarly, don't do this:
+
+```css
+button:hover {
+ background: var(--color-blue);
+}
+
+button:disabled {
+ background: var(--color-neutral);
+}
+```
-### DOs and DON'Ts
-- **DO** layer multiple shadows (comma-separated) for realistic soft depth effects.
-- **DO** use `filter: drop-shadow()` instead of `box-shadow` for non-rectangular shapes or transparent PNGs.
-- **DO** use elliptical `border-radius` (e.g., `10px / 20px`) for proportional curves without extra elements.
-- **DO** use `mix-blend-mode` and `background-blend-mode` for lighting overlays (limit scope with `isolation: isolate`).
-- **DO** use keywords before length values in `background-position` (e.g., `bottom 10px right 20px`).
-- **DO** use `clip-path` and `mask-image` for custom geometric reveals and smooth fade-outs.
-- **DO** use `::selection` to customize highlighted text colors.
-- **DO** use CSS Counters (`counter-reset`, `counter-increment`) for automated numbering visible in `::before`/`::after`.
+If we reorder the two rules, we will get a hover background on disabled buttons!
+Instead, do this:
-### Code Example: Advanced Visuals
```css
-.card {
- box-shadow:
- 0 1px 1px rgba(0,0,0,0.1),
- 0 2px 2px rgba(0,0,0,0.1),
- 0 4px 4px rgba(0,0,0,0.1); /* Layered shadow */
+button:hover:not(:disabled) {
+ background: var(--color-blue);
+}
- border-radius: 50px / 25px; /* Elliptical corners */
+button:disabled {
+ background: var(--color-neutral);
}
+```
+
+This works regardless of reordering, as the first rule does not overmatch.
+
+#### Prefer `@scope` over `:not()` for excluding (potentially deeply nested) subtrees
-.icon {
- filter: drop-shadow(0 5px 15px rgba(0,0,0,0.5)); /* Edge-following shadow */
+While `:not()` + descendant selectors can exclude subtrees, this works poorly for deeply nested structures.
+For example, `.card :not(.content *)` will not work as expected for nested cards.
+`@scope` fixes this as it takes hierarchical proximity into account:
+
+```css
+@scope (.card) to (.content) {
+ /* styles for elements inside .card but not inside .content */
}
+```
+
+This will work as expected even for nested cards.
+
+#### Overrides are fine for specialization
+
+This is fine:
+
+```css
+button {
+ background: var(--color-neutral);
+}
+
+button.primary {
+ background: var(--color-blue);
+}
+```
+
+Both rules express legitimate _intent_: buttons are generally neutral, but primary ones are blue.
+
+#### No global resets
+
+**DO NOT** use global resets (styles on `*`) as they cannot be overridden by web components or lower-priority cascade layers (without `!important`). Instead, apply reset styles to specific element types and/or conditions.
+
+### Nesting and scoping
+
+Use native CSS nesting to group related styles to the extent it improves maintainability and readability.
+
+Prefer `@scope` over nesting when proximity should matter more than pure specificity. This is common in selectors that can be nested in any order, but the closest matching one (in element -> ancestor order) should win, e.g. theming classes.
+
+For example this will not work as expected:
+```css
+.dark .invert { color-scheme: light }
+.light .invert { color-scheme: dark }
+```
+
+If `.invert` is nested within _both_ `.dark` and `.light`, it will always resolve to dark mode as both rules have the same specificity.
+Using `@scope` fixes this:
+
+```css
+@scope (.dark) {
+ .invert { color-scheme: light }
+}
+
+@scope (.light) {
+ .invert { color-scheme: dark }
+}
+```
+
+## 4. Interactivity
+
+### Focus management
+
+- Use `:focus-visible` to define custom focus rings, not `:focus`.
+- Do not remove the browser's default focus rings (via `outline: none`) without providing an alternative visible focus style.
+- Prefer `outline` over other properties (e.g. `box-shadow`) for focus rings. If you must rely on `box-shadow` for focus rings, provide an `outline`-based fallback for High Contrast Mode using the `forced-colors` media query.
+- Pair focus outlines with `outline-offset` to visually separate the ring from the element.
+
+### Touch targets
+
+- Interactive elements should be at least 24×24 CSS pixels (WCAG 2.5.8 AA). Enforce with `min-block-size` / `min-inline-size` or padding rather than `width` / `height`, so content can grow the target but not shrink it.
+- Bump targets up on coarse pointers: `@media (pointer: coarse) { ... }`.
+- **DON'T** use `touch-action: none` for custom gestures — it disables page scrolling through the element. Scope to the axis you actually need: `pan-y` for horizontal swipes (page still scrolls vertically), `pan-x` for vertical ones. Reserve `none` for elements where no native touch behavior makes sense (e.g. a drawing canvas).
+
+## 5. Design Tokens and Theming
+
+Use CSS custom properties on `:root` to define core design variables (colors, fonts, sizes, etc) used throughout the design, for visual consistency and to scale UI design across teams.
+**DO NOT** specify nontrivial styling values inline. E.g. `background: transparent` or `padding: 0` is ok, but `background: #f06` or `padding: .3em` are not.
+One exception is use cases where keeping code small and simple is far more important than long-term maintainability and evolution, such as testcases.
+
+Typically these are organized in tiers, with each tier building upon the previous one. For example:
+1. Tier 1: Literal design tokens (e.g. `--color-blue-10`, `--color-gray-90`, `--font-sans-serif`, `--size-xl` etc)
+2. Tier 2: Semantic design tokens (e.g. `--color-accent`, `--color-neutral`, `--font-body`, `--font-heading` etc)
+3. Tier 3: General UI design tokens (e.g. `--ui-border`, `--surface-bg-subtle` etc)
+4. Tier 4: Component-specific design tokens (e.g. `--button-bg-primary-hover`, `--button-border-color-secondary` etc)
+
+The smaller the scope of the use case, the fewer tiers it needs. E.g. a quick demo or toy app are fine with one tier. Do not overengineer.
+Check for any existing conventions around naming and levels before inventing your own.
+
+### Dark mode
+
+- Use `color-scheme: light dark` on `:root` to enable dark mode support that automatically adapts to the system setting. You can also specify `color-scheme` on individual elements to force a different value for that subtree (`light`/`dark` or `light dark` for the system default)
+- Use `light-dark()` to provide alternatives that automatically resolve based on the element's `color-scheme`.
+Typically this happens in Tier 2 or Tier 3 tokens.
+- IMPORTANT: When using `light-dark()` on an inherited `<color>` property, it will resolve to a specific color based on that element's `color-scheme` and inherit as that resolved color, not as a `light-dark()` value. It will NOT adapt to any descendant-specific `color-scheme` overrides. To keep `light-dark()` color tokens dynamic resolve them as late as possible by only passing them around as unregistered custom properties.
+
+
+### Forced Colors Mode
+
+In Forced Colors Mode (High Contrast on Windows), the browser overrides author colors with system keywords and strips `background-image`, `box-shadow`, and `border-image`.
+
+- Define system color fallbacks for color tokens using `@media (forced-colors: active)`.
+- **DON'T** rely on `background-image`, `box-shadow`, or `border-image` to convey borders, separators, or state — they disappear in forced colors (and often in print too). If you must, ensure there's an alternative in forced colors mode, such as `outline` or `border` with system color keywords (`CanvasText`, `LinkText`, `ButtonText`, `Highlight`, `GrayText`, etc.).
+- Use `forced-color-adjust: none` where color is essential information (syntax highlighter, color picker swatch). **DON'T** use `forced-color-adjust: none` just to preserve aesthetics.
+
+### Generating tints
+
+Before generating tints dynamically, check if you can use an existing, predefined, design token. This allows much more designer control and ensures consistency.
+
+If you need to generate lighter or darker colors dynamically:
+- **DO NOT** just adjust the lightness channel in `oklch`/`oklab` or `lch`/`lab`, e.g. `oklab(from var(--primary) 0.9 a b)`. While that is theoretically the correct way, browsers do not yet implement gamut mapping, so the resulting color is unpredictable.
+- You can use `color-mix()` to mix with white or black (preferably in `oklab`). This keeps the color safely in gamut, but tends to over-desaturate colors and produce washed out tints and shades.
+- You MAY combine lightness adjustment with any of the other methods (e.g. `color-mix(in oklab, oklch(from var(--primary) 0.9 c h), white 30%)`) for a balance between the two, but avoid going above 30% for the lightness adjustment.
+
+### Theming browser-generated UI
+
+Most browser-generated UI can be customized to some extent using CSS.
+Even if it requires modern features, it degrades gracefully in older browsers, and thus often does not require a polyfill or fallback.
+
+Before re-creating browser UI (form controls, scrollbars, selections, error messages, etc), first verify that:
+1. the browser UI cannot be customized enough for your needs, even with modern CSS,
+2. the desired customization is sufficiently critical to justify the tradeoffs of re-creating built-in UI — most notably losing accessible semantics, keyboard handling, IME, and AT integration that the native UI provides for free.
+
+Example customizations that are possible:
+- Use `::selection` to customize highlighted text colors.
+- **DON'T** apply `user-select: none` to content text — breaks copy-paste, translation tools, and AT "read from here" gestures. Limit it to chrome (drag handles, toolbars, redundant button labels).
+- Use `accent-color` to apply the page's accent color to any browser-generated UI.
+- Use `color-scheme` to have browser UI adapt to light/dark mode.
+- Use `scrollbar-color` to customize scrollbar colors and `scrollbar-width` to control scrollbar thickness — keep the thumb visibly distinct from the track (≥3:1), and don't set `scrollbar-width: none` on scrollable regions (use it only when scrolling is fully replaced by another affordance).
+- Use `:user-invalid` / `:user-valid` for validity styling, **not** `:invalid` / `:valid` — they only match after the user has interacted with the field, avoiding the hostile default of flagging required-empty fields as errors on page load.
+- Buttons and text fields (including `<textarea>`) can generally be styled as normal elements.
+- Use `font-size` to scale and other textual properties to control typography
+
+#### Styling textual fields (`<input>` & `<textarea>`)
+
+For most styling purposes (e.g. colors, borders, backgrounds, typography, etc) treat these elements as normal text containers.
+
+- Use `:placeholder-shown` and `::placeholder` to style input placeholders.
+- Use `field-sizing: content` to make text fields size to content.
+- For `<textarea>` elements, use `resize: vertical` to disable horizontal resizing or `resize: none` to disable all resizing.
+
+#### Multiple choice controls (select, radios, checkboxes)
+
+- To select one among many options presented in a dropdown: Use a `<select>` + `appearance: base-select` + `::picker(select)`. For more info see `branded-select-styling` (via `npx -p modern-web-guidance@latest -- modern-web retrieve "branded-select-styling"`)
+- Selecting one or more among multiple options laid out inline in the page: Use a `<input type=checkbox>` or `<input type=radio>` inside a `<label>` for each option. Style via `label:has(:checked)`.
+- Style checkboxes, radios and switches via `appearance: none` + generated content (`::before`/`::after`) or background images to draw the checked state.
+<!-- Customizable select listbox version currently buggy + this has much better browser support -->
+
+#### Non-textual `<input>`s (buttons, sliders, file inputs etc.)
+
+- File inputs: Use `::file-selector-button` to style the button.
+- Do not use `<input>` with a `type` of `button`, `submit` or `reset`. Use `<button>` instead and style it as a regular element.
+- Sliders: Use `appearance: none` + thumb pseudo-elements (`::-webkit-slider-thumb`, `::-moz-range-thumb`, etc) and track pseudo-elements (`::-webkit-slider-runnable-track`, `::-moz-range-track`, etc) for more granular control.
+
+## 6. Responsive design
+
+- Use `@container` queries to create component-driven responsive layouts that adapt to their parent container's size rather than the viewport.
+- Use dynamic viewport units (`dvh`, `dvw`) instead of `vh`/`vw` to prevent layout breakage when mobile browser UI elements (like address bars) appear or disappear.
+- Use `aspect-ratio` for media elements (like `<img>` and `<video>`) to reserve space during loading and prevent Cumulative Layout Shift (CLS).
+
+### Responsive Typography
+
+- **DO** combine viewport-relative and font-relative units in `clamp()` for font sizes that scale with the viewport size while ensuring they stay within a desired range. For example, `clamp(2rem, 1rem + 5vw, 4rem)`. Adjust the proportion of viewport-relative and font-relative units to control how quickly the font-size changes.
+- **DON'T** use `vw` alone for font-size without `clamp()`, as it can scale text too small or too large on extreme screens.
+
+## 7. Typography
+
+- Use unitless numbers for `line-height` (e.g., `1.5`) to ensure relative scaling during font-size inheritance.
+- Use `overflow-wrap: break-word` (or `anywhere`) to contain long URLs.
+- **DON'T** use `px` for font-size. Prefer `rem` to honor the user's browser font-size preferences (root font size), or `em` for contextual sizing.
+
+### Text wrapping
+
+- Use `text-wrap: balance` for balanced headlines and headline-like content (e.g. `<th>`)
+- Use `text-wrap: pretty` for long-form body text (paragraphs, blockquotes, etc.)
+- Use `text-wrap: balance` or `text-wrap: pretty` deliberately, **DO NOT** apply it on `*` as it does have a performance cost.
+- Avoid `text-wrap: balance` on elements with a visible box (backgrounds, borders, shadows, etc) as it does not change the container's width, it only affects how text wraps *within* that width. This can leave empty space at the end of the container, which is usually undesirable.
+
+## 8. Visual effects
+
+### Depth and texture
+
+- Layer multiple shadows for realistic soft depth effects.
+- Use `filter: drop-shadow()` instead of `box-shadow` for non-rectangular shapes or transparent PNGs.
+- Use `mix-blend-mode` and `background-blend-mode` for lighting overlays (limit scope with `isolation: isolate`)
+
+```css
.hero {
background-image: url('texture.png'), linear-gradient(to bottom, #fff, #eee);
background-blend-mode: soft-light;
}
+```
+
+### Shapes
-.portrait {
- clip-path: circle(50% at center);
- mask-image: linear-gradient(to bottom, black, transparent);
+- Use `corner-shape: squircle` for more aesthetically pleasing curves as a progressive enhancement over regular rounded corners.
+- Use elliptical `border-radius` (e.g., `10px / 20px`) for proportional curves without extra elements.
+
+### Gradients and `color-mix()`
+
+Use `in oklch` or `in oklab` to explicitly specify the interpolation color space for gradients or `color-mix()`.
+- `in oklch` preserves chroma better, but can more easily get out of device gamut, especially for bigger differences between colors
+- `in oklab` stays in gamut more easily (assuming in-gamut endpoints) but can create washed out desaturated colors in the middle, especially when interpolating between opposite hues.
+- *DON'T* use `in srgb` unless you have a specific reason to do so (e.g. you are building a color picker that needs to interpolate in srgb).
+
+#### Fallback
+
+Some pre-2024 browsers do not support gradient color interpolation space.
+To support these browsers, use the token only when its usage is safe by defining a variable:
+
+```css
+:root {
+ --in-oklab: ;
+ --in-oklch: ;
}
-```
+@supports (linear-gradient(in oklab, white, black)) {
+ :root {
+ --in-oklab: in oklab;
+ --in-oklch: in oklch;
+ }
+}
+```
-## 3. Native Selectors and Scoping
-Modern browser-native selectors reduce the need for preprocessors and complex state-tracking in JS.
+Then use like:
-### DOs and DON'Ts
-- **DO** use native CSS nesting to group related styles (3 levels max).
-- **DO** use `:has()` to style parents based on child state (e.g., `.form-group:has(:invalid)`). For more information, see the guides at `child-state-based-styling` (via `npx -p modern-web-guidance@latest -- modern-web retrieve "child-state-based-styling"`) and `content-based-styling` (via `npx -p modern-web-guidance@latest -- modern-web retrieve "content-based-styling"`).
-- **DON'T** nest `:has()` or use pseudo-elements inside `:has()` (browser API limitation).
-- **DO** use Attribute selectors (e.g., `[disabled]`) to style elements based on their state or metadata.
-- **DO** use `:where()` for baseline styles you want to be easily overridable (0 specificity).
-- **DO** use `:focus-visible` instead of `:focus` to hide focus rings for pointer interactions (mouse/touch) while preserving them for keyboard navigation and elements requiring text input.
-- **DO** pair focus outlines with `outline-offset` to separate the ring from the element.
-- **DON'T** use `outline: none` without providing a visible focus style.
-- **DON'T** rely on `box-shadow` for focus rings if you need to support Windows High Contrast Mode (use `outline` instead).
-- **DON'T** use `::before` or `::after` on replaced elements (`<img>`, `<input>`, `<video>`).
-
-### Code Example: Advanced Selectors
```css
.card {
- position: relative;
+ background: linear-gradient(to bottom var(--in-oklab), var(--accent-color), var(--darker));
+}
+```
- /* Accessible focus visible state */
- &:focus-visible {
- outline: 2px solid var(--accent);
- outline-offset: 4px; /* Separate ring from border */
- }
+- **Important:** If you use this technique, make sure there is always a non-empty gradient preamble without it, otherwise it will be a syntax error in older browsers.
+- You do NOT need this for `color-mix()`. If a browser supports `color-mix()`, it also supports its `in <color-space>` argument.
- /* Conditional styling based on content */
- &:has(img) { padding: 0; }
+### Patterns
- /* State management without extra classes */
- &:has(input:checked) { border-color: var(--active); }
+Many patterns can be created via CSS gradients + hard stops, and these can be more flexible and performant than SVGs or external images as they can have access to CSS variables and lengths from the surrounding context.
+You don't need to repeat the position twice — just use `0` or `0%` and gradient fixup will auto-adjust it.
- /* Shared styles without high specificity */
- :is(.title, .subtitle) {
- margin: 0;
- font-weight: bold;
- }
-}
+Examples below.
-/* Zero-specificity reset */
-:where(a) { color: blue; }
+Vertical stripes of `1em` width each:
+
+```css
+background: linear-gradient(to right, var(--color-1) 50%, var(--color-2) 0) 0 / 2em;
```
-### Functional Selectors Specificity Matrix
+Diagonal stripes of `1em` width each:
-| Selector | Specificity Weight | Primary Use Case |
-| :--- | :--- | :--- |
-| **`:where()`** | Exactly **0** | Baseline resets and design system defaults. |
-| **`:is()`** | Max specificity of its arguments | Reducing code duplication for shared styles. |
-| **`:has()`** | Max specificity of its arguments | Parent/relational styling based on child states or siblings. |
+```css
+background: repeating-linear-gradient(-45deg, var(--color-1) 0 1em, var(--color-2) 0 2em);
+```
-**Single-Sentence Mental Model**: "`:where()` = Spec-neutral resets, `:is()` = Spec-heavy grouping, `:has()` = Relational state."
+Checkerboard pattern with `1em` squares:
-## 4. Design Systems and Theming
-CSS Custom Properties (Variables) and modern color functions are the foundation of dynamic theming.
+```css
+background: repeating-conic-gradient(var(--color-1) 0 25%, var(--color-2) 0 50%) 0 / 2em 2em;
+```
-### DOs and DON'Ts
-- **DO** define design tokens as Custom Properties (`--brand-color`) on `:root`.
-- **DO** use `light-dark()` for simplified color scheme support (requires `color-scheme: light dark;`).
-- **DO** leverage `light-dark()` responding to *localized* `color-scheme` overrides (forcing dark theme on a subtree).
-- **DO** use `color-mix(in oklab, var(--primary) 70%, white 30%)` for dynamic tints outside of relative color syntax.
-- **DO** use **Relative Color Syntax** (`oklch(from var(--primary) l c h / 0.5)`) to derive tints dynamically.
+Polka dot with `.5em` radius dots spaced `2em` apart (horizontally/vertically — multiply by `sqrt(2)` for diagonal distance):
-### Code Example: Modern Theming
```css
-:root {
- color-scheme: light dark;
- --primary: oklch(60% 0.15 250);
-}
+--distance: 2em;
+--radius: .5em;
+--polka: radial-gradient(circle, var(--color-1) var(--radius), transparent calc(var(--radius) + 1px));
+background: var(--polka) 0 0, var(--polka) var(--distance) var(--distance) var(--color-2);
+background-size: calc(var(--distance) * 2) calc(var(--distance) * 2);
+```
-.dark-sidebar {
- color-scheme: dark; /* Forces child light-dark() values to use dark options */
+Simple pie chart:
+
+```css
+.pie {
+ --p: 80%;
+ width: 60px;
+ aspect-ratio: 1;
+ border-radius: 50%;
+ background: conic-gradient(var(--color-1) var(--p), transparent 0%) var(--color-2);
}
```
-### Theme Management Matrix
+**Important:** When using gradients to render charts, ensure there is a textual fallback for screen readers.
-| Feature | `light-dark()` | `@media (prefers-color-scheme)` |
-| :--- | :--- | :--- |
-| **Scope** | Local or Global | Strictly Global |
-| **Trigger Mechanism** | `color-scheme` property | OS/Browser preference |
-| **Component Overrides** | ✅ Easy | ❌ Difficult |
+## 9. Transitions & animations
-**Single-Sentence Mental Model**: "`light-dark()` = Contextual theme (supports local overrides), `@media` = Global preference (OS-level)."
+- Use `clip-path` and `mask-image` for custom geometric reveals and smooth fade-outs.
+- Use **Scroll-Driven Animations** (`animation-timeline: scroll()`) for non-essential scroll-bound effects instead of JS listeners.
+- Use **View Transitions** to animate between complex layout states seamlessly.
+
+### Performance
-## 5. Transitions, Animations, and Performance
Rendering performance is critical for smooth user experiences, especially in heavy DOM trees.
-### DOs and DON'Ts
-- **DO** only animate `transform` and `opacity` to ensure animations stay on the compositor thread.
-- **DO** use `translate` (or `transform: translate()`) instead of animating `top`/`left`/`right`/`bottom` to avoid triggering layout reflows and ensure smoother animations.
-- **DO** use `transition-behavior: allow-discrete` to animate layout properties like `display` or `<dialog>` state natively.
-- **DO** always pair `content-visibility` with `contain-intrinsic-size` to prevent scrollbar jumps (CLS).
-- **DO** use `contain: layout style paint` to isolate component rendering updates.
+- Prefer to animate `opacity` and `transform` (including individual transform properties, e.g. `translate` instead of `left/right/top/bottom`) to ensure animations stay on the compositor thread.
+- Use `transition-behavior: allow-discrete` + `@starting-style` to animate layout properties like `display` or `<dialog>` state natively.
+- Always pair `content-visibility` with `contain-intrinsic-size` to prevent scrollbar jumps (CLS).
+- Use `contain: layout style paint` to isolate component rendering updates.
+
+#### Code Example: Render Optimization
-### Code Example: Render Optimization
```css
.large-section {
content-visibility: auto;
@@ -196,95 +463,56 @@ Rendering performance is critical for smooth user experiences, especially in hea
}
```
+### Accessibility
+Use `prefers-reduced-motion` media queries to turn off heavy motion for users who prefer it.
-## 6. Modern Gradients and Color Spaces
-Create vibrant UI patterns without gray dead-zones using modern color spaces.
-
-### DOs and DON'Ts
-- **DO** use `in <color-space>` (e.g., `in oklch` or `in oklab`) to avoid vibrant colors washing out into grayscale in between.
-- **DO** use hard-edge color stops for sharp patterns (e.g., `red 50%, blue 50%`).
-- **DO** use `conic-gradient()` for progress rings or charts.
-- **DON'T** use `linear-gradient()` without a color space override if you are transitioning between highly saturated colors.
+**DO NOT** globally apply `animation-duration: 0.01ms;` globally as it can cause certain animations to become _more_ jarring.
+Either apply reduced motion versions on a case by case basis, or use a custom property like:
-### Code Example: Modern Gradients
```css
-/* Smooth, vibrant transition without standard gray dead-zones */
-.hero-gradient {
- background: linear-gradient(in oklch, var(--primary), var(--secondary));
+@property --animation-reduced {
+ syntax: "*";
+ inherits: false;
+ initial-value: none;
}
-/* Hard-edge stripes */
-.stripe-bg {
- background: linear-gradient(to right, var(--main) 50%, var(--accent) 50%);
+@media (prefers-reduced-motion: reduce) {
+ * {
+ animation: var(--animation-reduced) !important;
+ }
}
```
-## 7. Responsive Typography and Visual Sizing
-Use fluid and accessible typography that respects viewport widths and browser zoom.
-
-### DOs and DON'Ts
-- **DO** use unitless numbers for `line-height` (e.g., `1.5`) to ensure relative scaling during font-size inheritance.
-- **DO** use `clamp(min, preferred, max)` for fluid typography without media queries.
-- **DO** use standalone `min()` and `max()` to constrain values responsively.
-- **DO** use `text-wrap: balance` for short headlines (up to 4-6 lines) to prevent uneven orphans.
-- **DO** use `overflow-wrap: break-word` (or `anywhere`) to contain long URLs.
-- **DO** use `@container` queries to create component-driven responsive layouts that adapt to their parent container's size rather than the viewport.
-- **DO** use dynamic viewport units (`dvh`, `dvw`) instead of `vh`/`vw` to prevent layout breakage when mobile browser UI elements (like address bars) appear or disappear.
-- **DO** use `aspect-ratio` for media elements (like `<img>` and `<video>`) to reserve space during loading and prevent Cumulative Layout Shift (CLS).
-- **DON'T** use `px` for font-size. Prefer `rem` to honor the user's browser font-size preferences (root font size), as `px` values are absolute and may ignore user-defined defaults.
-- **DON'T** use `vw` alone for font-size without a min/max clamp, as it can scale text too small or too large on extreme screens.
-
-### Code Example: Fluid Typography
-```css
-h1 {
- font-size: clamp(2rem, 5vw + 1rem, 4rem); /* Fluid typography */
- text-wrap: balance;
- line-height: 1.2;
-}
+Then, reduced motion versions can be kept together with the original animations:
-.url-container {
- overflow-wrap: anywhere;
- hyphens: auto;
+```css
+progress:not([value]) {
+ animation: slide 1s infinite linear;
+ --animation-reduced: slide 20s infinite linear;
}
```
-## 8. Transitions, View Transitions, and Scroll Motion
-Leverage browser-native APIs for page navigations and viewport-bound animations.
+## 10. Generated content
-### DOs and DON'Ts
-- **DO** use `prefers-reduced-motion` media queries to turn off heavy motion for users who prefer it.
-- **DO** use **Scroll-Driven Animations** (`animation-timeline: scroll()`) for scroll-bound parallax effects instead of JS listeners.
-- **DO** use the **View Transitions API** (`view-transition-name`) to animate layouts seamlessly between page states.
+- **DON'T** use `content` to convey meaningful text (labels, state, instructions) — keep that in the DOM (WCAG F87). The alt text argument is harm reduction for cases where decoration accidentally carries meaning, not a license.
+- Use the alternative text argument of `content` to provide alt text for screen readers. E.g. `content: url(cloud.svg) / "Save";`
+- Use `content: "text" / "";` to prevent purely decorative text from being announced to screen readers.
+- **DON'T** use an empty alt text argument for images — they're already presentational by default. E.g. this is wrong: `content: url(cloud.svg) / "";`.
+- **DON'T** use the alt text argument to describe emojis unless the description differs from the official emoji name. E.g. don't do `content: "🎉" / "celebration";`, but `content: "🎉" / "Yay!";` is fine.
-### Code Example: Native Motion Primitives
-```css
-@media (prefers-reduced-motion: reduce) {
- * { animation-duration: 0.01ms !important; }
-}
+**ONLY** use the alt text argument when the text is different than the primary value and is not already present in the DOM. I.e. this is wrong:
-.scroll-tracker {
- animation: progress-tint linear;
- animation-timeline: scroll(); /* Native, zero-JS */
-}
+HTML:
+```html
+<button class="save">Save</button>
```
-## 9. Scoping and Shadow DOM
-Keep CSS architecture clean by explicitly scoping styles to components.
-
-### DOs and DON'Ts
-- **DO** use native `@scope` to isolate styles to a component boundary (e.g., `@scope (.card) to (.content) { ... }`).
-- **DO** use `:host` to style the custom element wrapper in Shadow DOM.
-- **DON'T** use global resets if you are relying on Shadow DOM isolation, as they will override local component styles unless scoped.
-
-### Code Example: Scoped CSS
+CSS:
```css
-/* Isolation without BEM side-effects */
-@scope (.media-object) {
- .title {
- font-weight: bold;
- }
+button.save::before {
+ content: url(cloud.svg) / "Save";
}
-
-
```
+
+A screen reader would read it out as "Save save".