Cutting Edge CSS: Nesting
Posted: | Tags: til webdevWhat I like about Sass and other CSS preprocessors, despite my limited usage of them, is the ability to nest CSS elements to assign style rules to children. Earlier this year the first version of the CSS Nesting Module specification was published by W3C. This brings the feature of CSS nesting to the browser! According to CanIUse, nesting is already supported by all major browsers as of this year.
Here’s a basic example, I have an article with a <h1>
and <h2>
header where I’d like all <h2>
headers within the article to be blue.
Here’s the HTML for the example article.
<article>
<h1>Header 1</h1>
<h2>Header 2</h2>
</article>
Without CSS nesting, I would write the following CSS.
article h2 {
color: blue;
}
With CSS nesting, I can use the &
within the parent element to select the child.
article {
& h2 {
color: blue;
}
}
If looking at this example you think the original method is possibly easier to understand, looking at some of the more complex examples from Chrome’s article might help sway you. Even if you don’t think that the article is a good read with many interactive demos to help wrap your head around the possibilities of nesting. MDN also has an article showing some interesting examples.
To wrap up, this feature has only been implemented in most major browsers this year, I’d still give it a while before people update to ensure full compatibility (that is if you don’t care about supporting IE, who does?). I will also include some links below to the mentioned and other resources that might be of interest.
Further reading:
- CSS Nesting - Can I Use? caniuse.com
- CSS Nesting - Chrome for Developers developer.chrome.com
- CSS Nesting Feature Detection - Bramus on Codepen codepen.io
- CSS Nesting Module - Specification www.w3.org
- Using CSS nesting - mdn web docs developer.mozilla.org