Nesting: future proofing CSS

by Silvia Mazzetta Date: 11-08-2021 css

Although not currently supported by browsers, there is a proposal for CSS nesting to support a feature that would provide better readability to native CSS, so in the future it is very likely that it will be supported and can be used directly.

The idea behind the CSS Nesting concept is the possibility of creating CSS rules (CSS code blocks) inside other CSS rules, nesting code and making it much easier to understand and maintain.

 

What does CSS nesting look like?

 
div {    
background: #fff;    
     p { color: red; }  
}
 

o for example

 
div {   
   background: #fff;    
        & p {      
             color: red;    
            }  
    }
 
 

If we are using PostCSS in our project, we can use it right now by translating it to native CSS with this tool, without having to wait for browsers to support it.

 

CSS nesting (&)

 

When writing CSS, we have to master and use basic CSS selectors and advanced CSS selectors to select the elements we want to style and write our specific rules. With CSS Nesting, it is not that we avoid using them, but we will use them less because by using indenting, we will be creating selectors in a "more logical for humans" way.

CSS Nesting is based on the possibility of including CSS blocks one inside the other (something that is not currently possible in native CSS), so it facilitates the organization of the code as it is read. The & character will be used to indicate that it is replaced by the entire parent selector we have (in this example, .item, but in cases with greater nesting will be longer):

 
.item {    
 padding: 10px;      
   & .warning {      
              background: red;      
              color: white;    
              }  
}
 

We have the .warning class inside the .item block, so that implies that only .warning classes that are inside the .item element will be CSS styled. This translates to native CSS as follows:

 
.item {
       padding: 10px;
      }    
.item .warning {
       background: red;
       color: white;
}
 

Perhaps with this example the advantage of CSS nesting is not yet clear, but as we write more code the advantages become apparent. If you have been working with CSS for any length of time, you will have noticed that one of the most complex things about CSS is maintaining code as it grows. This is where nesting shines.

Great advantages of using CSS Nesting:

 
  • The first level of nesting can be used as a "component" or entity.
  • It greatly simplifies CSS selectors, making them more intuitive (especially for novices).
  • By indenting, the code becomes much more readable.
  • By grouping with commas and nesting we get much more flexibility in less code.
  • Finding code snippets is much easier (if we are organized).
 

Let's complicate a little more an example code with CSS nesting:

 
.menu,  
.sidebar {    
background: black;    
color: white;
padding: 10px;  
    
    & a {      
         color: #333399;      
         font-size: 1.25rem;
         }      
    & .warning {      
         background: red;      
         color: white;    
         }  
}    

.warning {color: red;}
 

Notice that in this example we have the a elements and the .warning classes inside both .menu classes and .sidebar classes. This will allow us to substantially avoid repeating code. This example would translate to native CSS as we will see below:

 
.menu,  
.sidebar {    
background: black;    
color: white;   
 padding: 10px;  
}    
.menu a,
.sidebar a {    
color: #333399;    
font-size: 1.25rem;  
}    
.menu .warning,  
.sidebar .warning {    
background: red;    
color: white;  
}    
.warning {    
color: red;  
}
 

As you can see, it is much easier to read the top example with CSS nesting than the latter, where as it grows it is much less readable.

 

Nesting on the parent

 

An interesting detail to keep in mind is that we can nest selectors over the parent, simply by taking into account whether or not there is a space between the nesting & symbol.

 
.item {    
   background: grey;  
    
   &:hover {      
           background: red;    
           }  
}
 

In this code fragment, the nested selector &:hover is actually making reference to the selector .item:hover, that is, when we have the mouse over the element .item.

But on the other hand, if we were to add a space in the nested selector & :hover we would be referring to .item :hover, which has a different nuance than the previous one: we select when we have the mouse over an element that is inside .item.

 

The @nest rule

 

In some cases, with the & selector we can find some limitations. For this, with the @nest rule we can make the way of nesting selectors in our code more flexible and much more powerful.

For example, we can use the following code to reference any mention of the top-level parent:

 
.item {    
    background: grey;      

     @nest .container & {      
        background: green;    
     }  
}
 

The @nest rule allows us to warn the browser that there is a reference to the parent selector in a part of the selector that we are writing (and that may even be later). This will allow us, for example, to organize groups of CSS code where any mention of a certain element appears.

The equivalent code in native CSS would be the following:

 
.item {    
background: grey;  
}    
.container .item {    
background: green;  
}
 

As we can see, the & has been replaced by the selector that is nesting, so it works correctly.



Business vector created by jcomp - www.freepik.com
 
by Silvia Mazzetta Date: 11-08-2021 css hits : 3308  
 
Silvia Mazzetta

Silvia Mazzetta

Web Developer, Blogger, Creative Thinker, Social media enthusiast, Italian expat in Spain, mom of little 9 years old geek, founder of  @manoweb. A strong conceptual and creative thinker who has a keen interest in all things relate to the Internet. A technically savvy web developer, who has multiple  years of website design expertise behind her.  She turns conceptual ideas into highly creative visual digital products. 

 
 
 

Related Posts

New graphic window units - CSS

''Intercop 2022' is a project announced by Google, Microsoft, Apple and the Mozzilla Foundation to make all browsers offer the same web experience. The project has 15 focus areas and one…

Let's create a Color Picker from scratch with HTML5 Canvas, Javascript and CSS3

HTML5 Canvas is a technology that allows developers to generate real-time graphics and animations using JavaScript. It provides a blank canvas on which graphical elements, such as lines, shapes, images…

Why shouldn't we use black?

Nowadays it is becoming more and more common for web pages to have the option to set them in dark mode, or to base their aesthetics directly on black or…

How to make your own custom cursor for your website

When I started browsing different and original websites to learn from them, one of the first things that caught my attention was that some of them had their own cursors,…

Use the SRCSET attribute to improve your SEO

There is a new standard HTML attribute that can be used in conjunction with IMG called SRCSET. It is new and important as it allows webmasters to display different images…

Starting with Bootstrap-Vue step by step

Today we will show you how to use BootstrapVue, describe the installation process and show basic functionality. The project’s based on the world's most popular CSS framework - Bootstrap, for building…

Bootstrap 5 beta2. What offers?

Since the release of the Bootstrap 4 is three years, in this article we will present what is new in the world’s most popular framework for building responsive, mobile-first sites.…

Creating simple CSS spinner-loader

In today's article we will show you how to animate a basic loader that spins when some predefined action is defined, such as loading an image. That can be used…

How to use Parallax.js effect on your website

Today, we're going to write about the parallax effect, similar to parallax scrolling, and how to implement it to improve your landing page. In webdev, they say mobile first -…

How to make the website's dark mode persistent with Local Storage, CSS and JS

Recently we wrote about how to do a switchable alternative color mode or theme, a very useful and popular feature to websites. Today’s article is going to be about how…

The easiest way to align items using flexbox

With the release of flexbox in CSS, it has become an essential tool when placing elements next to each other, since, by default, the children of a display: flexare stacked…

Dark Mode on website using CSS and JavaScript

In today’s article we are going to learn how to build pretty much standard these days on the web pages and that is the alternative color mode and switching between…

Clicky