CSS Nesting

CSS Nesting

CSS nesting is a feature that allows you to nest one style rule inside another, with the selector of the child rule relative to the selector of the parent rule. This feature enhances the readability, modularity, and maintainability of CSS stylesheets. It also potentially helps reduce the size of CSS files, thereby decreasing the amount of data downloaded by users.

The ability to use nesting in CSS has been around for well over 10 years now. However, this feature was previously completely unsupported on any browser without the help of a CSS preprocessor like Sass or Less. The exploration of bringing nesting capabilities directly to CSS led to the development of the CSS nesting module.

The ampersand (&) is used in CSS nesting to reference the parent selector from within a nested ruleset. It comes in handy when you want to create a more specific selector, like an element that has both of two classes. The ampersand always refers to the parent selector when nesting. It can be placed multiple times, appended to reverse the context of the rules, and used with pseudo classes.

As of 2023, CSS nesting is newly available across major browsers. It has partial support on Chrome from version 112 through to 119, Microsoft Edge from version 112 up to the latest version, Safari from version 16.5-17.1, and Opera from 98 to the latest version. Full support is available on Chrome from version 120, Safari from version 17.2, and Firefox from version 117. You can stay up-to-date regarding the browser compatibility of native CSS nesting on CanIUse.

Source: “Research and Document the concept of CSS nesting. Discuss the origins of CSS nesting. Discuss the use of the ampersand as nesting selector. Discuss browser support based on data from the caniuse.com website.” Copilot in Edge, Microsoft, 29 Mar. 2024.

Example

Both of the h2 tags on this page are being styled by CSS nesting code. The nesting code is giving the h2 tags within the wrapper class a purple color. The ampersand in the code is referring to the wrapper class. I would use CSS nesting in a project if there were certain style rules for tags, classes, or IDs that I wanted to apply within a containing (parent) class or ID and I wanted those rules to only apply within that containing class or ID. I can also group rules by parent selector, making the overall stylesheet easier to read.