Avoid Using ID Selectors in CSS

HTML allows an identifier (that is, an id attribute) to be used once per document. As a result, rule sets that use ID selectors are hard to repurpose. Doing so typically involves using a list of ID selectors—for example, #sidebar-feature, #sidebar-sports , and so on.

Identifiers also have a high degree of specificity, and require longer selectors to override declarations. In the example that follows, we need to use #sidebar.sports and #sidebar.local to undo the background color of #sidebar :

/* Avoid doing this in your CSS */
#sidebar {

float: right;

width: 25%;

background: #eee;

}

#sidebar.sports {

background: #d5e3ff;

}

#sidebar.local {

background: #ffcccc;

}

Instead, we can use a simple .sidebar class selector:

.sidebar {

float: right; width: 25%; background: #eee;

}

.sports {

background: #d5e3ff;

}

.local {

background: #ffcccc;

}

Not only does this save a few bytes, but our .sports and .Local, rules can now be used with other elements.

Using an attribute selector such as [id=sidebar] avoids the higher specificity of an identifier. Though it lacks the reusability of a class selector, the low specificity means we can avoid selector chaining.

Let’s discuss a selector such as #content articLe.sports tabLe#stats tr:nth-chiLd(even) td:Last-chiLd . Not only is it absurdly long, but with a specificity of 2,3,4, it’s also not reusable. How many possible instances of this selector can there be in your markup?

Let’s make this better. We can immediately trim our selector to #stats tr:nth-chiLd(even) td:Last-chiLd . It’s specific enough to do the job. An even simpler approach is to use a class name such as .stats . It’s a much shorter selector, and those styles aren’t limited to #stats tables.

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

Leave a Reply

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