Avoid Chaining Selectors in CSS

Another way to minimize specificity is to avoid chaining selectors. Selectors such as .message.warning have a specificity of 0,2,0. Higher specificity means they’re hard to override. What’s more, chaining classes may cause side effects. Here’s an example:

.message {

background: #eee;

border: 2px solid #333;

border-radius: 1em;

padding: 1em;

}

.message.error {

background: #f30;

color: #fff;

}

.error {

background: #ff0;

border-color: #fc0;

}

Using <p cLass=”message”> with this CSS gives us a nice gray box with a dark gray border.

Using <p cLass=”message error”> , however, gives us the background of .message.error and the border of .error , as shown below.

The only way to override a chained selector is to use an even more specific selector. To be rid of the yellow border, we’d need to add a class name or type selector to the chain, such as .message.warning.exception or div.message.warning . It’s more expedient to create a new class instead.

If you do find yourself chaining selectors, go back to the drawing board. Either the design has inconsistencies, or you’re chaining prematurely in an attempt to prevent problems you don’t yet have. The maintenance headaches you’ll prevent and the flexibility you’ll gain are worth it.

Source: Brown Tiffany B (2021), CSS , SitePoint; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *