Cascading style sheets (better known as CSS) they are the design language (and one of the three great bases, along with HTML and JavaScript) of the World Wide Web, the language that allows developers to format web pages by applying styles that alter aspects such as colors, fonts or spacing.
And now, this language born in 1996 is perhaps on the verge of experience one of the biggest changes in its history. As published by Miriam Suzanne, a member of the CSS Working Group of the W3C (the body in charge of establishing the standards of web technologies), the passage of the CSS Nesting specification from the current ‘draft for editors’ phase has been approved to that of ‘first draft of public work’.
This introduces you to the proposal review process known as the ‘Recommendation Track’, which can lead to its inclusion in the standard version of the CSS language. The online version, still classified as’ editors’ draft ‘, specifies that the proposal was available “for discussion only” and that “its publication here does not imply endorsement of its content by the W3C.”
But, What is ‘CSS Nesting’ (literally ‘CSS nesting’)? Fundamentally, it is about allowing CSS rules to be expressed in a nested way, including code blocks within each other, an option not available natively for now.
All this in order to:
- Make the code more readable.
- Increase its modularity and ease of maintenance style sheets.
- Reduce duplication of code.
Let’s see an example:
Nowadays, when we write CSS, we are forced to master the ‘CSS selectors’ to define the rules applicable to our site and to specify which elements we want to apply a certain style to. The whole point of CSS nesting is that we have to use them much less often, because using the indentation we will already be supplying its work (in a way, also, much more readable for humans).
This will entail some syntax changes. For example, ‘&’ will become the nesting selector for setting conditional rules. So in
.ejemplo {
background: grey;
&: hover {background: red; }}
In this example, the selector &: hover is really referring to .example: hover; that is, to those cases in which we have the mouse over the ‘example’ element.
Work now with the new draft
But,what to do if we liked the idea and we want to start working with CSS following the recommendations of the draft? Easy: browsers wouldn’t understand the new syntax and the resulting web could not be displayed correctly.
Unless, of course, we used a CSS transformation tool like PostCSS, which already has a plug-in (postcss-nesting) to transform nested CSS into the CSS conforming to the current standard …
… So, using terminal tools like npm and npx, we can install PostCSS and use it later to transform files .pcss (nested) in .css.
Both this option and a future officialization of the ‘CSS Nesting’ constitute alternatives to the use of CSS preprocessors as popular as SASS (although these have other attractions besides the use of nesting).