CSS Nesting

Nesting in CSS was first implemented by preprocessors like Sass and Less. It was later introduced into native CSS Selectors Level 4, which is the most recent specification for CSS selectors.

The ampersand, when used as a nested selector, refers to the parent element which it is nested inside of. This allows for the selection of child elements as it relates to the heirarchal structure of HTML markup.

As of January 2022, CSS nesting only had partial support in major browsers. However, more recent versions of most major browsers have been updated to fully support CSS nesting.

Nesting Example

The following example contains 6 divs, each with the class of "card". The only difference is that the first 3 are nested inside of a div called "cards", while the last 3 are not. The only divs that received the given styles were the ones that are nested within the "cards" div.

The ampersand is used to only select a "card" that is nested inside of the "cards" div.

I can use this method whenever I only want to select elements that are children of a particular parent element.

Nested

Lorem ipsum dolor sit amet consectetur adipisicing elit. Iure et fugit error illo odit laudantium suscipit cupiditate eum, magni quisquam!

Nested

Lorem ipsum dolor sit amet consectetur adipisicing elit. Iure et fugit error illo odit laudantium suscipit cupiditate eum, magni quisquam!

Nested

Lorem ipsum dolor sit amet consectetur adipisicing elit. Iure et fugit error illo odit laudantium suscipit cupiditate eum, magni quisquam!

Not nested

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Cum voluptatum quis ratione in id totam unde facilis tempore repellat. Hic!

Not nested

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Cum voluptatum quis ratione in id totam unde facilis tempore repellat. Hic!

Not nested

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Cum voluptatum quis ratione in id totam unde facilis tempore repellat. Hic!

Citation

"Describe the origins of CSS nesting. Also describe how to use the ampersand as a nesting selector in CSS. Also show browser support for CSS nesting based on data from caniuse.com", ChatGPT, 3.5, OpenAI, 01 Apr. 2024, https://chat.openai.com/c/a9031d27-a2b9-4af5-8bdd-da661fa2d5e3