CSS Nesting

Created Using Generative AI

  1. CSS nesting refers to the ability to nest one style rule inside another. Instead of writing the same selector repeatedly to style specific child elements or pseudo-selectors, you can nest them under a single selector. This approach helps group related styles and creates a nested hierarchy in your CSS.
  2. Origin of CSS Nesting
    -Developers recognized the need for nesting capabilities directly within CSS.
    -The motivation came from the success of nesting in tools like SCSS and LESS.
    -The goal was to reduce duplication, enhance readability, and improve maintainability of CSS code.
    -Fast forward to 2023, native CSS nesting became an officially recognized feature in the CSS Specification.
    -Unlike preprocessors, native nesting is parsed directly by browsers, eliminating the need for additional tools or compilation steps.
  3. The ampersand (&) is a powerful feature in Sass (and other preprocessors like Less) that simplifies CSS nesting.
    -When you nest styles, the & refers to the parent selector. It allows you to create more specific selectors within the nesting structure.
    -When you want to target an element with both of two classes. You can achieve this using the &
    -You can use the & to write pseudo-classes in a less repetitive way
    -The & works seamlessly with child combinator (>), adjacent sibling combinator (+), and general sibling combinator (~)
    -You can also qualify a selector by placing the & on the right
  4. Browser support of CSS Nesting based on CanIUse
    Chrome: CSS nesting is available from version 112 onwards 12. It’s supported in the latest versions of Chrome.
    Safari: Safari supports CSS nesting starting from version 16.5 12. If you’re using Safari, you’re good to go!
    Firefox: Although Firefox doesn’t natively support CSS nesting yet, it’s expected to arrive later in 2023 (likely in version 115) behind a feature flag 2.
    Edge: CSS nesting is available in Edge from version 120 onwards 13. So, if you’re using Edge, you’re covered too.

Code example

This code example below uses CSS nesting to style parent and child. I created a separate SASS file called nesting where I styled the element. Ampersand in this case was used to create a more specific selector. CSS nesting in a project could keep related styles together. Nesting in forms would improve readability. Besides, it would help with media queries, pseudo classes, to create specific rules, style isolated elements.

                    
                        p { color: black; }
                        body { background-color: white; }
                    
                

Resources

Prompts:concept of CSS nesting, origins of CSS nesting, use of ampersand as nesting selector, browser support of CSS nesting based on caniuse.comMicrosoft Edge Copilot,Microsoft, Apr 2, 2024