CSS Nesting

CSS Nesting

Now you can nest CSS with out using any CSS preprocessor

CSS nesting will be available in Chrome behind a developer flag starting from v109. CSS nesting allows you to nest one style inside another.

You can nest hover selectors, media queries etc which can be dependent on the parent element or be the parent element, which will be effective to create styles easily and produce mode clean and readable code structure.

Here I'm using PostCSS repossessor for the example but it will be there on the native CSS.

.container{
  height:100px;
  background-color:green;

  & p{
    color:white;

    & a{
      color:orange;
    }
  }

  @media(min-width:600px){
    & {
      background:blue;
    }  
  }
}

Here & p{ color:white; } stands for .container p{color: white;} , similarly, the media queries work with the "&" sign. Here &{background:blue;} stands for .container{background:blue;} .


.container{
  &:hover{
    & a{
     color:violet;
    }
  }
}

above code applies the violet color to the "a" tag when the hover selector is activated on the container. CSS nesting helps us to implement this kind of style logic easily.

But we should avoid over-nesting because it can lead to specificity issues.

What is specificity?

If 2 or more styling rules are pointing to the same element the selector with the highest specificity wins and that rule will be applied to the element.

level:

  • Inline styles

  • IDs

  • Classes

  • Elements and pseudo-elements

if bellow is the HTML code :
<p id="test" class="testClass" >Hello</p>

Then, CSS

#test{
    color:red;
}
.testClass{
    color:blue;
}

Then here red color will be applied, due to the higher specificity of id than class.

Conclusion:

  • Nesting helps to build more clean and readable code and allows media queries to be applied in the same space.

  • Over-nesting can cause confusion

If you have any issues or questions about it, feel free to contact me. Thank you 🌟 for reading! like, share and subscribe to my newsletter for more!

🔗Debasish Lenka

Did you find this article valuable?

Support Debasish Lenka by becoming a sponsor. Any amount is appreciated!