CSS Beginner

CSS Selectors and Specificity

Imran Nadwi
107 views 30 min read

Understanding CSS Selectors

Selectors are how we target which HTML elements to style. Think of them like finding items on a page: "Style all paragraphs", "Style elements with class name 'button'", or "Style the element with ID 'header'". Learning selectors is crucial because you cannot style what you cannot select.

1. Element Selectors (Most Basic)

Target all elements of a specific type by using the element's HTML tag name:

p {
    color: blue;
    font-size: 16px;
}

/* This styles ALL paragraph elements */

h1 {
    text-align: center;
}

/* This styles ALL h1 headings */

a {
    color: green;
    text-decoration: none;
}

/* This styles ALL links */

When to use: For styling all instances of an element on the page (like all paragraphs or all links)

Pros: Simple, applies to all matching elements automatically

Cons: Can't target specific elements, affects every element of that type

2. Class Selectors (Most Common in Real Projects)

Use a dot (.) followed by the class name. Classes are reusable and can apply to any HTML element:

.button {
    background-color: blue;
    color: white;
    padding: 10px 20px;
    border-radius: 5px;
    cursor: pointer;
}

.highlight {
    background-color: yellow;
    font-weight: bold;
}

.success {
    color: green;
    font-weight: bold;
}

In your HTML:

<button class="button">Click Me</button>
<p class="highlight">This text is important!</p>
<p class="success">Operation completed successfully</p>
<a href="#" class="button">Link Button</a> <!-- Reuse the button class -->

When to use: For styling reusable components that might appear multiple times

Pros: Reusable across many elements, specific enough to target certain elements, you can add multiple classes to one element

Cons: Slightly more specific than element selectors (more weight in CSS)

3. ID Selectors (Use Sparingly)

Use a hash (#) followed by the ID name. Each ID should be unique on a page—use only once per ID:

#header {
    background-color: navy;
    padding: 20px;
    color: white;
}

#main-content {
    width: 80%;
    margin: 20px auto;
}

#footer {
    background-color: gray;
    padding: 10px;
    text-align: center;
}

In your HTML:

<div id="header">
    <h1>My Website</h1>
</div>
<div id="main-content">
    <p>Content here</p>
</div>
<div id="footer">
    <p>© 2024 My Website</p>
</div>

When to use: For unique page sections that appear only once (like header, footer, main content area)

Pros: Very specific and powerful

Cons: Very high specificity (hard to override), can't reuse, bad for component-based design

4. Combining Selectors

Multiple Selectors (Apply Same Styles)

Use commas to apply the same styles to multiple selectors:

h1, h2, h3 {
    color: navy;
    font-family: Georgia, serif;
}

/* This styles all h1, h2, and h3 elements with the same rules */

.button, .link, a {
    text-decoration: none;
    cursor: pointer;
}

Descendant Selector (Parent > Child)

Use a space to select elements inside other elements:

.card p {
    color: gray;
    margin: 10px 0;
}

/* This styles only <p> tags INSIDE elements with class "card" */

#header h1 {
    font-size: 32px;
}

/* This styles h1 tags INSIDE the element with ID "header" */

In your HTML:

<div class="card">
    <h2>Card Title</h2>
    <p>This paragraph is inside .card</p> <!-- Gets gray color -->
</div>
<p>This paragraph is outside .card</p> <!-- Does NOT get gray color -->

Understanding CSS Specificity

When multiple CSS rules target the same element, CSS uses specificity to decide which rule wins. Higher specificity wins.

Specificity Hierarchy (from lowest to highest)

1. Element selectors (p, h1, div)          - Specificity: 1
2. Class selectors (.button, .header)      - Specificity: 10
3. ID selectors (#main, #footer)           - Specificity: 100
4. Inline styles (style="color: blue")     - Specificity: 1000
5. !important keyword (color: blue !important) - Specificity: Highest (use rarely)

Real Example - Understanding Specificity

/* Specificity: 1 */
p {
    color: blue;
}

/* Specificity: 10 - This wins! */
.important {
    color: red;
}

/* Specificity: 100 - This would win over class selector */
#special {
    color: green;
}

In your HTML:

<p>Blue text</p> <!-- Uses element selector: blue -->
<p class="important">Red text</p> <!-- Uses class selector: red (beats element selector) -->
<p id="special" class="important">Green text</p> <!-- Uses ID selector: green (beats class selector) -->

When Specificity Matters

/* This rule */
.button {
    background-color: blue;
}

/* Cannot be overridden by this rule (lower specificity) */
button {
    background-color: red; /* This rule loses! */
}

/* But can be overridden by this (higher specificity) */
.button.primary {
    background-color: green; /* This rule wins! */
}

Practical Tips for Selectors

  • Use classes for most styling - They're reusable and flexible without being too specific
  • Use element selectors for global styles - Like default paragraph styling
  • Use ID selectors sparingly - Only for unique page sections, avoid using ID selectors in stylesheets for better reusability
  • Avoid !important - It makes CSS hard to override and creates problems later
  • Be specific enough, but not too specific - Overly specific selectors are hard to reuse and override
  • Use logical class names - `.button-primary` is clearer than `.btn-blue`

Summary

You now understand:

  • How element selectors work and when to use them
  • How class selectors work and why they're most common in real projects
  • How ID selectors work and why to use them sparingly
  • How to combine selectors using commas and descendant combinator
  • CSS specificity and why higher specificity selectors win over lower ones

Mastering selectors is the foundation for CSS. In the next lesson, we'll learn about the box model, which controls spacing and sizing of elements.