CSS Nesting
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
Subscribe to my newsletter
Read articles from Debasish Lenka directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Debasish Lenka
Debasish Lenka
Hey ๐ My name is Debasish, I'm a System Engineer and a passionate Web Developer who loves to experiment with new technologies and build projects. I like to share and showcase my tips and knowledge on this blog. Since you are here feel free to browse through some of my posts, I'm sure you will find something useful and interesting. Hope you are feeling excited!