Using Type and Attribute Selectors with Caution in CSS

It’s good to keep specificity low, but be careful about the selectors you use to accomplish that. Type and attribute selectors can be the most bothersome.

Type selectors are element selectors such as p , button , and hi . Attribute selectors include those such as [type=checkbox] . Style declarations applied to these selectors will be applied to every such element across the site. Let’s look at another example using buttons, this time with an element selector:

button {

background: #FFC107;

border: 1px outset #FF9800;

display: block;

font: bold 16px / 1.5 sans-serif;

margin: 1rem auto;

width: 50%;

padding: .5rem;

}

This seems innocuous enough. But what if we want to create a button that’s styled differently? Let’s create a .tab-rounded button for tab panels:

<div class=”tabs”>

<button type=”button” role=”tab” aria-selected=’true” aria-controls=”tab1″ id=”tab-id”

class=”tab-rounded”>Tab 1</button>

</div>

<div tabindex=”0″ role=”tabpanel” id=”tab1″ aria-labelledby=”tab-id”>

<p>This is the tab 1 text</p>

</div>

Now we need to write CSS to override every line that we don’t want our rounded button to inherit from the button rule set:

.tab-rounded {

background: inherit;

border: 1px solid #333;

border-bottom: 0;     /* We only need borders on three sides for tabs */

border-radius: 3px 3px 0 0;

diplay: inline-block;

font-weight: normal;

margin: .5rem 0 0;

width: auto;

padding: 1rem 2rem;

}

We’d still need many of these declarations to override browser defaults, but what if we assign our button styles to a .default class instead? We can then drop the display , font-weight and width declarations from our .tab-rounded rule set. That’s a 21% reduction in size:

.default {

background: #FFC107;

border: 1px outset #FF9800;

display: block;

font: bold 16px / 1.5 sans-serif;

margin: 1rem auto;

width: 50%;

padding: .5rem;

}

.tab-rounded {

background: inherit;

border: 1px solid #333;

border-bottom: 0;

border-radius: 3px 3px 0 0;

padding: 1rem 2rem;

}

Just as importantly, avoiding type and attribute selectors reduces the risk of styling conflicts. A developer working on one module or document won’t inadvertently add a rule that creates a side effect in another module or document.

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

Leave a Reply

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