Choosing Low-specificity Selectors in CSS

Err on the side of using low-specificity selectors. They make it easier to reuse your CSS, and extend patterns in new ways.

Consider the following:

button[type=button] {

background: #333;

border: 3px solid #333;

border-radius: 100px;

color: white;

line-height: 1;

font-size: 2rem;

font-family: inherit;

padding: .5rem 1rem;

}

This gives us a charcoal-gray button with white text and rounded ends, as shown in the following image.

Let’s add some styles for a close button. We’ll use a .close class, as shown below:

button[type=button] {

background: #333;

border: 3px solid #333;

border-radius: 100px;

color: white;

line-height: 1;

font-size: 6rem;

font-family: inherit;

padding: .5rem 1rem;

}

.close {

width: 9rem;

height: 9rem;

background: #c00;

border: 0;

border-bottom: 5px solid #c00;

font-size: 3rem;

line-height: 0;

padding: 0;

}

Now we have two charcoal-gray buttons with white text and rounded ends.

What’s happening? Our button[type=button] selector has a specificity of 0,1,1. However, .close is a class selector. Its specificity is only 0,1,0. As a result, most of our .dose rules don’t get applied to <button type=”button” class=”close”> .

We can ensure that our .close styles are applied by either:

  • changing .close to button[type=button].close
  • making button[type=button] less specific

The second option adds fewer bytes, so let’s use that:

[type=button] {

background: #333;

border: 3px solid #333;

border-radius: 100px;

color: white;

line-height: 1;

font-size: 6rem;

padding: .5rem;

}

.close {

width: 9rem;

height: 9rem;

background: #c00;

border: 0;

border-bottom: 5px solid #c00;

font-size: 3rem;

line-height: 0;

}

Changing the specificity of our selector

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

Leave a Reply

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