Selectors and Specificity

Explore CSS selector types and how specificity determines which styles apply.

🎯 Introduction

CSS controls the appearance of websites, and selectors are the foundation for applying styles. There are many selector types, and their specificity helps determine which styles take precedence and how a page looks. This article explains selector types, specificity, and how to use !important effectively to write clearer, more efficient CSS.

🧩 What Types of Selectors Are Available?

CSS provides several types of selectors. Here are some common ones:

Selector typeDescriptionExample
Type selectorSelects elements of a given HTML typediv, p
Class selectorSelects elements with a given class.class-name
ID selectorSelects an element with a given ID#id-name
Attribute selectorSelects elements with a given attribute[type="text"]
Pseudo-class selectorSelects elements in a particular state:hover, :first-child
Pseudo-element selectorSelects part of an element::before, ::after

Each selector has its own uses and strengths. Class selectors work well for reusable styles, while ID selectors target unique elements.

🔗 Selecting Elements by Relationship (Combinators)

Combinators express relationships between elements. Combining selectors lets you target elements more precisely. Common combinators include:

CombinatorDescriptionExample
DescendantSelects matching descendants of an elementdiv p
ChildSelects matching direct children of an elementul > li
Next-siblingSelects a matching sibling immediately after an elementh1 + p
Subsequent-siblingSelects matching siblings after an elementh1 ~ p

Combinators give you more precise control over which elements receive styles. For example, use div p to select every p inside a div.

⚖️ Understanding Specificity

When multiple selectors match an element, specificity helps determine which styles apply. It depends on the types and number of selectors. A common teaching model uses four values (a, b, c, d), including inline styles:

  • a: Inline styles, such as style="..."
  • b: Number of ID selectors
  • c: Number of class, pseudo-class, and attribute selectors
  • d: Number of type and pseudo-element selectors

Compare these values as follows:

  1. Start with the first value. If the values differ, the larger value wins.
  2. If the first values match, compare the second values, and continue in order.
  3. If all values match, the rule that appears later takes precedence.
Selector exampleSpecificity
div(0, 0, 0, 1)
.class-name(0, 0, 1, 0)
#id-name(0, 1, 0, 0)
div.class-name(0, 0, 1, 1)
div#id-name(0, 1, 0, 1)
style="..."(1, 0, 0, 0)

In this comparison, inline styles take precedence, followed by ID selectors, class selectors, and finally type selectors.

🚨 When to Use !important

Sometimes you need to give a declaration priority using !important. For example:

p {
    color: red !important;
}

!important gives a declaration priority over normal declarations regardless of their selector specificity. Use it carefully, because overuse makes styles harder to maintain.

Possible Use Cases

  • Overriding earlier styles from the end of a stylesheet.
  • Ensuring a declaration applies when other styles would otherwise override it.
Minimize the use of !important to keep your CSS predictable and manageable.

❓ Knowledge Check

Q1: What do CSS selectors do?

CSS selectors identify the elements to which styles apply. They let developers control a page's appearance and layout.

Q2: How is specificity calculated?

Specificity depends on the types and number of selectors. The four-value teaching model (a, b, c, d) also accounts for inline styles.

Q3: What are the risks of using !important?

Overusing !important makes styles harder to maintain and debug. Use it sparingly and only when necessary.

🧪 Exercises

Exercise 1: Create a Simple Stylesheet

Create a CSS file containing several selector types and apply it to an HTML page.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Selector Exercise</title>
        <link rel="stylesheet" href="styles.css" />
    </head>
    <body>
        <div class="container">
            <h1 id="header">Selectors and Specificity</h1>
            <p class="text">This example demonstrates selectors.</p>
        </div>
    </body>
</html>

Exercise 2: Experiment with Specificity

In your CSS file, add ID and class selectors to change the styles applied to elements, and observe the result.

#header {
    color: blue;
}

.text {
    color: green;
}

Copy the code into your editor and preview the result!


🎉 You have learned about selector types, specificity, and when to use !important!