Chapter 8: Cascade layers and nesting
The introduction explains why maintainable CSS needs more than working layouts and introduces newer CSS features as tools for organizing styles and controlling the cascade.
After this chapter you will be able to
- Maintainable CSS organization. Explain why making CSS work is not enough: it also needs to remain understandable and changeable as a project grows.
- Built-in cascade organization tools. Describe the contrast between relying on prescribed methodologies and naming patterns and using newer CSS features for organization and explicit cascade control.
- Specificity versus intended priority. Explain why a simple .button rule cannot override certain styles from a:any-link on a link styled as a button, and describe the classic specificity-based fix.
- Layer definition and order. Describe how to define layers with @layer and how their order affects conflicting declarations. Explain that, in the examples here, a later-defined layer takes precedence over an earlier one.
- Layers within the cascade. Explain how layer priority relates to selector specificity and what happens to styles outside any layer.
- First-reference layer priority. Explain that a layer’s priority is set by its first appearance in the stylesheet, and that referencing the same layer again adds styles without changing its priority.
- Unlayered style precedence. Explain how styles outside every layer compare with layered styles, and why the author generally recommends placing styles in layers.
- Important declaration priority reversal. Explain how !important changes the priority order between layers, using the reduced-motion declarations as an example.
- Nested layer organization. Describe how nested layers divide a parent layer and how priority works among the nested layers and styles directly in the parent.
- Reverting the current layer. Explain that revert-layer removes values applied in the current layer so values from previous layers can take effect, unlike revert, which removes author styles to restore user-agent defaults. Describe how this lets links in .blog-content use global link styles instead of higher-priority button-like styles.
- Layer order and flexibility. Explain that the recommended layer organization is a starting point: later layers take priority over earlier ones, and a project can omit layers it does not need.
- Modern purpose of resets. Explain that resets were once used to address substantial differences between browsers, but are now more useful for changing browser defaults to ones you prefer. Give an example such as border-box sizing, form-control fonts, or the body margin.
- Reusable reset layer boundaries. Describe the reset layer as a small, mostly reusable place to adjust user-agent styles, leaving site-specific design decisions to later layers.
- Site-wide theme custom properties. Explain why site-wide custom properties, especially colors, belong early in a low-priority theme layer.
- Global layer defaults. Explain that the global, or base, layer holds default styles applied throughout a website, such as fonts, colors, headings, and links.
- Layout layer responsibilities. Explain why the layout layer handles the page’s overall structure before the details within it, including major sections, grids, or columns.
- Modules layer purpose. Explain what belongs in the modules layer and why it contains most of a page’s styles.
- Focused utility classes. Describe utility classes as narrowly focused helpers for one simple action, such as centering text or hiding an element, rather than full modules.
- Utility layer priority. Explain why the author places utility classes in a high-priority layer instead of relying on !important.
- Optional state layer placement. Explain what a states layer would contain, where the author prefers to put those styles, and why neither arrangement is mandatory.
- Concise selector grouping. Explain how :is() replaces a repetitive selector list and which elements the resulting selector matches.
- Highest argument specificity. Explain how the specificity of :is() is determined, including whether the argument that matches a particular element changes it.
- Forgiving selectors with is. Explain why placing selector alternatives inside :is() can preserve a rule when a browser does not recognize one of them, using :user-invalid and .invalid as the example.
- Zero-specificity :where() selectors. Explain how :where() reduces selector specificity without changing what the selector matches, and calculate the specificity of :where(#login-form) input.
- Nested selector relationships. Explain how placing a rule inside another makes its selector relative to the parent selector, and why the .card example targets the same elements with less repetition.
- Specificity and nesting depth. Explain how specificity is determined for a nested rule and why the section recommends limiting nesting depth.
- Compound selectors with ampersand. Explain why nesting .is-open inside .modal does not select the same element as .modal.is-open, and how &.is-open produces the intended compound selector.
- Reordered selectors and context. Explain how placing & later in a nested selector changes selector order, and describe the maintenance caution given here.
- Nesting selector translation. Explain that nesting is syntactic sugar and that a nested & is translated by wrapping the parent selector in :is(), including when the parent is a selector list.
- Specificity of nested selectors. Explain why a nested selector using & can inherit the highest specificity in a parent selector list, even when a lower-specificity alternative matches the element.
- Unexpected nested selector matches. Describe how the :is() translation can make a nested selector match a title when the card and footer appear in either ancestral order.
- Nested at-rule declarations. Explain how @media, @layer, and @supports rules can be nested inside a ruleset, and which element their declarations style when no nested selector is present.
- Declaration order before nested blocks. Justify placing nonnested declarations before nested blocks in a ruleset, including the effect on cascade order and on older browsers.
What it builds on
- The cascade (chapter 1) · The earlier explanation of the cascade gives context for why controlling it matters.
- Selector specificity (chapter 1) · Assumes familiarity with comparing selector specificity.
- Stylesheet origin (chapter 1) · The earlier discussion of reversed origin priority for !important styles
- The revert keyword (chapter 1) · The revert keyword’s effect on author styles.
- Special values (chapter 1) · The special CSS keyword values introduced earlier.
- Custom properties (aka CSS variables) (chapter 2) · Introduces CSS custom properties.
- Progressively enhancing selectors (chapter 1) · Progressively enhancing selectors while retaining behavior in browsers with less support.
- Source order (chapter 1) · Source order as a factor in the cascade.
Section by section
Introduction
The introduction explains why maintainable CSS needs more than working layouts and introduces newer CSS features as tools for organizing styles and controlling the cascade.
- Maintainable CSS organization: Explain why making CSS work is not enough: it also needs to remain understandable and changeable as a project grows.
Why it matters: This is the problem the chapter’s organization tools are meant to address. - Built-in cascade organization tools: Describe the contrast between relying on prescribed methodologies and naming patterns and using newer CSS features for organization and explicit cascade control.
Why it matters: It explains why the chapter turns to CSS features rather than relying only on conventions.
Key terms: code organization, brittle, first-class features, cascade, naming patterns
8.1 Manipulating the cascade with layers
This section shows how selector specificity can prevent a CSS rule from taking precedence even when the author intends it to.
- Specificity versus intended priority: Explain why a simple .button rule cannot override certain styles from a:any-link on a link styled as a button, and describe the classic specificity-based fix.
Why it matters: It explains why a button-like link can retain general link styles despite a more targeted-looking button rule.
Key terms: selector specificity, source order, a:any-link, .button
8.1.1 Defining layers
This section shows how to define cascade layers and explains their priority, browser-support implications, and naming options.
- Layer definition and order: Describe how to define layers with @layer and how their order affects conflicting declarations. Explain that, in the examples here, a later-defined layer takes precedence over an earlier one.
Why it matters: Layer order gives you a way to control which group of styles wins. - Layers within the cascade: Explain how layer priority relates to selector specificity and what happens to styles outside any layer.
Why it matters: This explains why a selector may lose despite being more specific, or why an unlayered rule may win. - Named and anonymous layers: Distinguish named layers from anonymous layers and explain the practical benefit of names.
Why it matters: Names make layers easier to reuse and keep organized as a stylesheet grows. - Browser support tradeoff: Explain the browser-support risk to check before using cascade layers.
Why it matters: The consequences of unsupported layers may affect whether they are suitable for your site's audience. - Imported stylesheet layers: Describe how an imported stylesheet can be assigned to a layer and the limitation stated for HTML link tags.
Why it matters: This lets an external CSS import participate in your layer organization.
Key terms: @layer, cascade layers, layer priority, origin, inline styles, selector specificity, unlayered styles, named layers, anonymous layers, browser support
8.1.2 Layer order and priority
This section explains how cascade-layer order sets style priority, how !important reverses that order, and how nested layers provide finer organization.
- First-reference layer priority: Explain that a layer’s priority is set by its first appearance in the stylesheet, and that referencing the same layer again adds styles without changing its priority.
Why it matters: This lets you predict which layer wins even when its styles appear in multiple places. - Up-front layer declarations: Describe how to declare several layers in a single comma-separated @layer at-rule before adding styles, and why the section recommends doing so.
Why it matters: A visible, deliberate layer order is easier to maintain than one established accidentally across the stylesheet. - Unlayered style precedence: Explain how styles outside every layer compare with layered styles, and why the author generally recommends placing styles in layers.
Why it matters: A rule outside the layer plan can override layered rules unexpectedly. - Important declaration priority reversal: Explain how !important changes the priority order between layers, using the reduced-motion declarations as an example.
Why it matters: The reversal lets a foundational rule, such as the reduced-motion rule, resist overrides from later layers. - Nested layer organization: Describe how nested layers divide a parent layer and how priority works among the nested layers and styles directly in the parent.
Why it matters: Nested layers give a part of the stylesheet its own finer-grained priority structure.
Key terms: cascade layers, priority, @layer, @layer at-rule, precedence, unlayered styles, highest-priority layer, !important, prefers-reduced-motion, reset layer
8.1.3 The revert-layer keyword
Explains how revert-layer restores values from earlier cascade layers and how the all property can apply that reset to multiple properties.
- Reverting the current layer: Explain that revert-layer removes values applied in the current layer so values from previous layers can take effect, unlike revert, which removes author styles to restore user-agent defaults. Describe how this lets links in .blog-content use global link styles instead of higher-priority button-like styles.
Why it matters: It gives you a way to undo a higher-priority layer’s styling without discarding styles established in earlier layers. - Resetting properties with all: Describe how setting all to revert-layer reverts multiple properties at once, and state that all accepts only the five special keyword values named here.
Why it matters: It avoids writing a separate reset for each property when several styles need reverting.
Key terms: revert-layer, revert, current layer, previous layers, global layer, theme layer, all, initial, inherit, unset
8.2 A recommended organization for cascade layers
Introduces a flexible template for organizing cascade layers by priority, with later layers taking precedence over earlier ones.
- Layer order and flexibility: Explain that the recommended layer organization is a starting point: later layers take priority over earlier ones, and a project can omit layers it does not need.
Why it matters: This gives you a way to plan which styles should win without treating the suggested layer list as mandatory.
Key terms: cascade layers, layer organization, priority, reset
8.2.1 Reset layer
This section explains why a reset layer is still useful and why it should contain small, reusable adjustments to browser defaults rather than site-specific design.
- Modern purpose of resets: Explain that resets were once used to address substantial differences between browsers, but are now more useful for changing browser defaults to ones you prefer. Give an example such as border-box sizing, form-control fonts, or the body margin.
Why it matters: It clarifies what problem a reset solves in a modern stylesheet. - Reusable reset layer boundaries: Describe the reset layer as a small, mostly reusable place to adjust user-agent styles, leaving site-specific design decisions to later layers.
Why it matters: Keeping the reset separate makes it a dependable starting point for multiple projects.
Key terms: reset stylesheet, user-agent styles, border box sizing, reset layer, site-specific design decisions
8.2.2 Theme layer
Explains what belongs in a low-priority theme layer, why site-wide values go there, and when custom properties should stay with a specific component.
- Site-wide theme custom properties: Explain why site-wide custom properties, especially colors, belong early in a low-priority theme layer.
Why it matters: This gives shared theme values a convenient home without making local changes difficult. - Browser-facing theme properties: Describe what accent-color and color-scheme contribute to a site's theme.
Why it matters: These properties help browser-rendered controls fit the site's theme. - Component-specific custom property placement: Distinguish site-wide custom properties from those used only by a specific part of the page, and describe where to define each.
Why it matters: Keeping local values near the styles that use them avoids treating every custom property as a global theme setting.
Key terms: theme layer, custom properties, colors, accent-color, color-scheme, site-wide custom properties, layout layer, modules layer, --image-radius
8.2.3 Global layer
This subsection explains the global layer’s role in setting site-wide default styles and shows how it uses theme-layer values.
- Global layer defaults: Explain that the global, or base, layer holds default styles applied throughout a website, such as fonts, colors, headings, and links.
Why it matters: It gives site-wide defaults a clear home in the layer organization. - Global style selectors and values: Describe why global styles mostly use tag selectors, and state that they can use theme-layer custom properties and set font sizes, including larger fonts at wider viewport widths.
Why it matters: It connects site-wide element defaults to the theme values and responsive typography described here.
Key terms: global layer, base layer, default values, tag selectors, custom properties, theme layer, responsive behavior
8.2.4 Layout layer
Explains what belongs in a layout layer and how to apply different page layouts while managing selector specificity and reusable styles.
- Layout layer responsibilities: Explain why the layout layer handles the page’s overall structure before the details within it, including major sections, grids, or columns.
Why it matters: It helps you separate page structure from the finer styling of its contents. - Page layout selection: Describe how a shared stylesheet can define different page structures and how a page selects one of them.
Why it matters: It lets several page types use one stylesheet without requiring the same structure. - Layout selector tradeoffs: Explain why IDs are usable for layout selectors here, and when a class is the better choice.
Why it matters: It prevents selector specificity or repeated IDs from getting in the way of reusable layouts.
Key terms: layout layer, high-level layout, homepage ID, article ID, selector specificity, layer priority, ID, class name, l- prefix, modules layer
8.2.5 Modules layer
This section identifies the modules layer as the main home for reusable page components and gives brief guidance on naming, portability, and organizing its styles.
- Modules layer purpose: Explain what belongs in the modules layer and why it contains most of a page’s styles.
Why it matters: It helps you decide where the bulk of a site’s component styles should go. - Reusable module design: Describe the section’s general rule for naming and building modules.
Why it matters: These guidelines make a module useful in more than one place on a page. - Nested layer option: Explain why nested layers may be useful within the modules layer and how firmly the section recommends a strategy.
Why it matters: It presents nested layers as an organizational option, not a prescribed structure.
Key terms: modules layer, modules, components, module, unique name, nested layers
8.2.6 Utilities layer
This section explains when to use narrowly focused utility classes and why placing them in a high-priority cascade layer makes them reliable helpers.
- Focused utility classes: Describe utility classes as narrowly focused helpers for one simple action, such as centering text or hiding an element, rather than full modules.
Why it matters: This helps you choose a small helper instead of building a module for a single styling task. - Utility layer priority: Explain why the author places utility classes in a high-priority layer instead of relying on !important.
Why it matters: A helper meant to make a specific change is most useful when other styles do not unexpectedly override it.
Key terms: utility classes, modules, utilities layer, !important, high-priority layer, utility class
8.2.7 Additional layers
This section presents an optional layer for module states and emphasizes that the recommended layer structure can be adapted.
- Optional state layer placement: Explain what a states layer would contain, where the author prefers to put those styles, and why neither arrangement is mandatory.
Why it matters: It helps you organize changing module styles without treating one layer scheme as compulsory.
Key terms: states, modules, sublayer
8.3 The :is() and :where() pseudo-classes
Introduces :is() as a way to shorten repetitive selectors, then explains its matching, specificity, and pseudo-element restriction.
- Concise selector grouping: Explain how :is() replaces a repetitive selector list and which elements the resulting selector matches.
Why it matters: It lets you recognize when a shorter selector expresses the same matches as a repetitive list. - Highest argument specificity: Explain how the specificity of :is() is determined, including whether the argument that matches a particular element changes it.
Why it matters: A highly specific option can affect the selector’s specificity even for elements matched by another option. - Pseudo-element argument restriction: Distinguish pseudo-elements from pseudo-classes when describing which selectors can be used inside :is().
Why it matters: This distinction helps you avoid an invalid :is() selector.
Key terms: :is(), pseudo-class, selectors, specificity, pseudo-element selectors, pseudo-classes
8.3.1 More forgiving selectors
The section shows how :is() lets a valid selector continue to work when another selector is unsupported.
- Forgiving selectors with is: Explain why placing selector alternatives inside :is() can preserve a rule when a browser does not recognize one of them, using :user-invalid and .invalid as the example.
Why it matters: It lets newer pseudo-classes enhance a stylesheet without preventing older browsers from using a supported alternative.
Key terms: :is(), :user-invalid, .invalid, progressive enhancement
8.3.2 Manipulating specificity
This subsection shows how :where() and :is() can lower or raise selector specificity, and recommends keeping specificity low when possible.
- Zero-specificity :where() selectors: Explain how :where() reduces selector specificity without changing what the selector matches, and calculate the specificity of :where(#login-form) input.
Why it matters: It lets you target elements precisely without making a rule unnecessarily hard to override, including by styles in the same layer. - Specificity-raising :is() arguments: Describe how a high-specificity argument to :is() can raise a selector's specificity, and state why the author generally discourages doing so.
Why it matters: The contrast with :where() shows that these similar-looking pseudo-classes can have very different effects on the cascade.
Key terms: :where(), specificity, same layer, :is(), #fake-id
8.4 Nesting
Introduces CSS nesting by showing how it groups related rules, preserves their targets and specificity, and calls for care with nesting depth and browser support.
- Nested selector relationships: Explain how placing a rule inside another makes its selector relative to the parent selector, and why the .card example targets the same elements with less repetition.
Why it matters: Nesting can make related styles easier to read and a repeated class name easier to change. - Specificity and nesting depth: Explain how specificity is determined for a nested rule and why the section recommends limiting nesting depth.
Why it matters: Keeping nesting shallow helps avoid selectors with more specificity than the styles need. - Production browser support: Describe the browser-support caution to consider before using CSS nesting on a production site.
Why it matters: Support in major browsers does not guarantee that every site's users have a version that supports nesting.
Key terms: nesting, parent rule, child rule, selector, selector specificity, final assembled selector, CSS nesting, usage statistics
8.4.1 Using the nesting selector
This section explains how the CSS nesting selector (&) changes where an outer selector appears in a nested selector, along with a limitation and an obsolete syntax restriction.
- Compound selectors with ampersand: Explain why nesting .is-open inside .modal does not select the same element as .modal.is-open, and how &.is-open produces the intended compound selector.
Why it matters: The placement of & determines whether a rule targets an element itself or one of its descendants. - Element states and pseudo-elements: Describe how the nesting selector can target a state or pseudo-element of the outer element.
Why it matters: This lets related styles for an element and its variations stay together. - Reordered selectors and context: Explain how placing & later in a nested selector changes selector order, and describe the maintenance caution given here.
Why it matters: Reordered nesting is useful, but it can tie a component’s styling to where the component appears. - Nesting syntax limitations: Distinguish the inability of CSS nesting to merge partial class names from the former restriction on nested tag selectors.
Why it matters: Separating a real limitation from an obsolete one helps avoid incorrect selectors and outdated nesting advice.
Key terms: nesting selector, compound selector, descendant combinator, &:hover, &::after, selector order, context, partial class names, tag selector, & h3
8.4.2 Understanding the nuances of the nesting selector
This section explains how CSS nesting translates to ordinary selectors and why that translation can affect specificity and which elements match.
- Nesting selector translation: Explain that nesting is syntactic sugar and that a nested & is translated by wrapping the parent selector in :is(), including when the parent is a selector list.
Why it matters: Thinking about the translated selector makes nesting’s less obvious behavior easier to predict. - Specificity of nested selectors: Explain why a nested selector using & can inherit the highest specificity in a parent selector list, even when a lower-specificity alternative matches the element.
Why it matters: A high-specificity parent alternative can make a nested rule harder to override than its matching alternative suggests. - Unexpected nested selector matches: Describe how the :is() translation can make a nested selector match a title when the card and footer appear in either ancestral order.
Why it matters: Reading the translated selector helps explain matches that might otherwise look like nesting bugs.
Key terms: nesting, syntactic sugar, desugars, nesting selector, :is(), selector list, specificity, parent selector, &, nested selector
8.4.3 Nesting media queries and other at-rules
This section shows how nested at-rules keep related styles together and why ordinary declarations should come before nested blocks.
- Nested at-rule declarations: Explain how @media, @layer, and @supports rules can be nested inside a ruleset, and which element their declarations style when no nested selector is present.
Why it matters: You can keep an element’s related styles together without rewriting its selector for each at-rule. - Declaration order before nested blocks: Justify placing nonnested declarations before nested blocks in a ruleset, including the effect on cascade order and on older browsers.
Why it matters: Putting ordinary declarations first makes the effective cascade order clearer and helps older browsers retain basic styling.
Key terms: nesting, @media, @layer, @supports, parent selector, nonnested declarations, nested blocks, source order, cascade, graceful degradation
8.5 Summary
Where this is used later
- Defining modules (chapter 9) · Defining modules continues the focus on organizing CSS for change.
- Modules and global styles (chapter 9) · The earlier introduction to cascade layers.
- From here to there (chapter 15) · Understanding why reduced-motion declarations can take precedence over later transition styles
- Naming color variables (chapter 11) · Names color variables that can serve as shared theme values.
- (chapter intro) (chapter 9) · Introduces the modules layer in the recommended layer organization.
Concepts explained in this chapter
- cascade layerA nested cascade layer is a cascade layer defined within another cascade layer and ordered relative to its sibling layers.
- CSS nestingCSS nesting is a language feature that allows a style rule to contain nested selectors and declarations representing related selector structures.
- :is()The CSS :is() pseudo-class matches an element if it matches at least one selector in its argument list and contributes the specificity of its most specific argument.
- specificityA numeric representation of a selector's counts of IDs, classes, and tags, ordered from highest to lowest priority.
- type selectorA CSS selector that matches elements by their element or tag name.
- CSS variableA CSS custom property is an author-defined CSS property whose name begins with two hyphens and whose value can be substituted with the var() function.
- CSS source orderSource order is the relative position of declarations in stylesheets or included stylesheets, which breaks ties when other cascade criteria are equal.
- cascadeThe CSS cascade is the process that selects a property value from competing declarations according to their applicability, origin, importance, specificity, and source order.
- moduleA module is a reusable, relatively small unit of page structure and styling that is independent of its surrounding page context.
- prefers-reduced-motionThe prefers-reduced-motion media feature indicates whether a user has requested reduced nonessential motion.
- descendant selectorA descendant selector is a CSS selector that matches an element occurring anywhere inside an ancestor matched by another selector.
- layoutA page layout is the overall spatial arrangement of a web page's major sections and content regions.
- CSSCSS is a stylesheet language for describing the presentation of structured documents such as HTML pages.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
