CSS Nesting is a feature that allows developers to write CSS rules inside other rules, mirroring the structure of HTML elements. It improves readability, reduces redundancy, and makes stylesheets more maintainable—especially in complex UI designs.
Traditionally, CSS does not support nested rules, and developers had to rely on preprocessors like Sass or Less to use nesting. However, native CSS Nesting is now being adopted in modern browsers as part of the evolving CSS specification.
The ampersand (&) in CSS nesting is a special character used as a reference to the parent selector when writing nested CSS rules.
Preprocessors Era: The idea of CSS nesting came from preprocessors like Sass, Less, and Stylus, which allowed developers to write nested styles, compile them into standard CSS, and thereby simplify code management.
Native CSS Proposal: Due to the popularity of preprocessors and developer demand, the CSS Working Group started discussing native nesting in the CSS Nesting Module Level 1 specification. The proposal aimed to add nesting directly into the CSS language.
Official Spec Status: As of now, the spec is considered a Working Draft but is increasingly implemented in modern browsers.
Citation: "What is the origin of CSS nesting and why is it used?", ChatGPT, GPT-4, OpenAI, https://chatgpt.com/c/67f1d87e-840c-8001-902a-96d72b1941ff
Citation: "What is the ampersand used for in CSS nesting?", ChatGPT, GPT-4, OpenAI, https://chatgpt.com/c/67f1d87e-840c-8001-902a-96d72b1941ff
<footer class="foot-links">
<a class="home" href="#">© 2024 - Chris</a>
<a href="#">CSS</a>
<a href="#">HTML</a>
</footer>
a {
padding: 10px 16px;
color: rgb(18, 18, 18);
text-shadow: 1px 1px black;
background-color: rgba(11, 8, 202, 0.1);
border: 2px solid rgb(6, 6, 6);
border-radius: 5px;
text-decoration: none;
font-weight: bold;
transition: background-color 0.3s, transform 0.1s ease;
&:hover {
color: rgb(240, 241, 246);
background-color: rgba(5, 20, 161, 0.852);
}
&:active {
animation: clickEffect 0.2s ease;
transform: scale(0.95);
}
}
The ampersand is used in the example to target the parent element, which in this case is the anchor for the links in the footer. Its making the :hover attach to the anchors and apply the color and background when hovered. The second ampersand is also attaching to the anchors. Although this time it is triggering an animation when the anchor is clicked. By using the ampersand and nesting in a project the code will be cleaner and easier to read. It is a great way to keep the CSS more organized and less redundant on projects.