Specificity

[todo]

  • Selectors
  • Cascade
  • Inheritance
  • Specificity

Nope

When you stare into the abyss — the abyss stares back:

// Good
.search_button {}

// Bad
.header .search-box input[type=search] + .button {}

Chaining selectors creates a specifity mess.

Reducing specificity

[todo]

Nesting conventions: https://twitter.com/sturobson/status/525019409107386368

Element qualification

Append an element suffix to the class name to clarify the markup pattern (not by qualifying the element type). This keeps specificity low, and improves selector performance.

// Good
.breadcrumbs-list {}

// Bad
ol.breadcrumbs {}

Element suffixes

Always use suffixes with these elements:

.some-form {}
.some-list {}
.some-table {}

Selector specificity

<!-- Good -->
<header class="account-header">
    <nav class="account-header-nav">
        <a href="#" class="account-header-link">Account</a>
        <a href="#" class="account-header-link">Sign Out</a>
    </nav>
</header>

<!-- Bad -->
<header>
    <nav>
        <a href="#">Account</a>
        <a href="#">Sign Out</a>
    </nav>
</header>
// Good
.account-header {}
.account-header-nav {}
.account-header-link {}

// Bad
header {}
header nav {}
header nav a {}

IDs and classes

Always avoid using an ID if possible.

!important

Never use !important to raise the specificity of a rule. In well architected CSS this should never be required. If you think it is, rewrite the rules being inherited with high specificity that are causing problems.

// Bad
.some-form {
    color: #000 !important;
}

Resources