Skip to main content

Command Palette

Search for a command to run...

CSS Selectors: How to Talk to Your HTML Elements

Updated
10 min read

Why CSS Selectors Are Needed

Imagine you're in a room with 50 people and you want to tell someone to raise their hand. You have a few options:

"Everyone wearing a red shirt, raise your hand." (targets multiple people by a common trait) "The person named Rahul, raise your hand." (targets one specific person) "All teachers, raise your hand." (targets everyone with a certain role)

CSS selectors work the same way. You have HTML elements on your page, and you need a way to tell the browser "apply this styling to these specific elements."

Without selectors, you'd have to write inline styles on every single element:

<p style="color: blue;">Paragraph 1</p>
<p style="color: blue;">Paragraph 2</p>
<p style="color: blue;">Paragraph 3</p>

That's repetitive, hard to maintain, and defeats the entire purpose of CSS. Selectors let you write styles once and apply them to multiple elements:

p {
  color: blue;
}

Now all paragraphs are blue. Change one line of CSS, update them all. That's the power of selectors.

Element Selector: Talking to All Elements of a Type

The element selector targets all elements of a specific type. It's the most basic selector.

Syntax

elementName {
  property: value;
}

Example: Styling All Paragraphs

HTML:

<p>First paragraph</p>
<p>Second paragraph</p>
<p>Third paragraph</p>

CSS:

p {
  color: purple;
  font-size: 18px;
}

Result: All three paragraphs are purple with 18px font size.

Example: Styling All Headings

h1 {
  color: navy;
  font-size: 36px;
}

h2 {
  color: teal;
  font-size: 28px;
}

Every h1 on your page gets one style, every h2 gets another.

When to Use Element Selectors

Use element selectors for base styles that apply to all instances of that element. Setting default font for all paragraphs. Removing underlines from all links. Standardizing heading sizes.

It's like setting a dress code for a category of people: "All teachers wear formal attire."

Class Selector: Targeting Elements with a Common Label

Class selectors target elements that share a class attribute. Multiple elements can have the same class, and one element can have multiple classes.

Syntax

.className {
  property: value;
}

The dot before the name tells CSS this is a class selector.

Example: Styling Elements with a Class

HTML:

<p class="highlight">This paragraph is highlighted</p>
<p>This paragraph is not</p>
<p class="highlight">This one is highlighted too</p>

CSS:

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

Result: Only the paragraphs with class="highlight" get the yellow background and bold text.

Multiple Classes on One Element

HTML:

<p class="highlight important">Warning message</p>

CSS:

.highlight {
  background-color: yellow;
}

.important {
  color: red;
  font-weight: bold;
}

Result: The paragraph gets both styles. Yellow background from .highlight and red bold text from .important.

Same Class on Different Elements

HTML:

<h2 class="card-title">Heading Title</h2>
<p class="card-body">Paragraph content</p>
<div class="card-title">Div with same class</div>

CSS:

.card-title {
  color: darkblue;
  font-size: 24px;
}

Result: Both the h2 and the div get the same styling, even though they're different element types.

When to Use Class Selectors

Classes are the workhorse of CSS. Use them for reusable styles that apply to multiple elements. Styling components (cards, buttons, navigation items). Creating utility classes (text alignment, spacing). Grouping elements by purpose, not by element type.

It's like giving people badges at a conference: "Everyone with a 'speaker' badge gets backstage access." Multiple people can be speakers, and one person can have multiple badges.

ID Selector: Targeting One Specific Element

ID selectors target a single unique element. An ID should only appear once per page.

Syntax

#idName {
  property: value;
}

The hash symbol tells CSS this is an ID selector.

Example: Styling a Unique Element

HTML:

<div id="header">Main Header</div>
<div id="footer">Footer Content</div>

CSS:

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

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

Result: Each ID gets its own unique styling.

When to Use ID Selectors

Use IDs sparingly in CSS. Modern best practices prefer classes for styling. IDs are better suited for JavaScript hooks and page anchors. Some valid uses include styling the main header, main footer, or main navigation (truly unique elements), creating anchor links (jump to section), and targeting elements with JavaScript.

It's like someone's Aadhar number. Only one person has that specific ID. You use it when you need to identify one specific individual, not a group.

ID vs Class: The Key Difference

An ID can only be used once per page. A class can be used unlimited times. An element can only have one ID. An element can have multiple classes. IDs have higher specificity (we'll cover this soon). Classes are more flexible and reusable.

Example showing the difference:

<!-- WRONG: Same ID used twice -->
<div id="box">Box 1</div>
<div id="box">Box 2</div>

<!-- CORRECT: Same class used multiple times -->
<div class="box">Box 1</div>
<div class="box">Box 2</div>

<!-- CORRECT: Element with both ID and class -->
<div id="main-sidebar" class="sidebar">Sidebar</div>

Group Selectors: Applying Same Styles to Multiple Elements

Sometimes you want to apply the same styles to multiple different elements. Instead of repeating yourself, use group selectors.

Syntax

selector1, selector2, selector3 {
  property: value;
}

Separate selectors with commas.

Example: Styling All Headings

Instead of:

h1 {
  font-family: Arial;
  color: darkblue;
}

h2 {
  font-family: Arial;
  color: darkblue;
}

h3 {
  font-family: Arial;
  color: darkblue;
}

Write:

h1, h2, h3 {
  font-family: Arial;
  color: darkblue;
}

Same result, way less code.

Example: Multiple Classes

.btn-primary, .btn-secondary, .btn-danger {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
}

All three button classes share the same base styles.

Mixing Selector Types

h1, .special-heading, #page-title {
  text-transform: uppercase;
}

You can group element selectors, class selectors, and ID selectors together.

When to Use Group Selectors

Use group selectors when multiple different elements need identical styles. Resetting margins/padding on multiple elements. Applying typography to all headings. Setting common button styles.

It's like making an announcement: "All students, all teachers, and all staff, please assemble in the hall."

Descendant Selectors: Targeting Nested Elements

Descendant selectors target elements that are inside other elements. They let you be more specific about which elements to style.

Syntax

ancestor descendant {
  property: value;
}

Separate selectors with a space.

HTML:

<nav>
  <a href="#">Home</a>
  <a href="#">About</a>
</nav>

<div>
  <a href="#">Regular link</a>
</div>

CSS:

nav a {
  color: white;
  text-decoration: none;
}

Result: Only the links inside nav are styled. The link in the div remains unchanged.

Example: Nested Lists

HTML:

<div class="sidebar">
  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
  </ul>
</div>

<ul>
  <li>Item 3</li>
  <li>Item 4</li>
</ul>

CSS:

.sidebar ul {
  background-color: lightgray;
}

Result: Only the ul inside .sidebar gets the gray background.

Multiple Levels Deep

div p span {
  color: red;
}

This targets span elements that are inside p elements that are inside div elements. It works no matter how deeply nested.

HTML that matches:

<div>
  <p>
    <span>This will be red</span>
  </p>
</div>

Combining with Classes

.card .title {
  font-size: 24px;
  font-weight: bold;
}

This targets any element with class title that's inside an element with class card.

When to Use Descendant Selectors

Use descendant selectors to scope styles to specific areas. Styling navigation links differently from content links. Styling elements inside cards or components. Creating contextual styles based on parent containers.

It's like saying "All students in Room 5, stand up" instead of "All students everywhere, stand up."

Descendant vs Direct Child

Note: Descendant selectors target any level of nesting. There's also a direct child selector (>), but we're keeping it simple for now.

/* Descendant: any level */
div p {
  color: blue;
}

/* Matches all of these */
<div><p>Blue</p></div>
<div><section><p>Also blue</p></section></div>

Basic Selector Priority (Specificity)

When multiple CSS rules target the same element, the browser needs to decide which rule wins. This is called specificity.

The Basic Hierarchy

From lowest to highest priority:

  1. Element selectors (lowest)

  2. Class selectors

  3. ID selectors (highest)

  4. Inline styles (even higher, but avoid these)

Example: Class Beats Element

HTML:

<p class="special">What color am I?</p>

CSS:

p {
  color: blue;
}

.special {
  color: red;
}

Result: The paragraph is red, not blue. The class selector is more specific than the element selector.

Example: ID Beats Class

HTML:

<p class="special" id="unique">What color am I?</p>

CSS:

p {
  color: blue;
}

.special {
  color: red;
}

#unique {
  color: green;
}

Result: The paragraph is green. ID selector beats both class and element selectors.

Combining Selectors Increases Specificity

/* Less specific */
.title {
  color: blue;
}

/* More specific */
div.title {
  color: red;
}

If an element is <div class="title">, it will be red because div.title is more specific than just .title.

Practical Rule of Thumb

For most styling, stick to classes. Use element selectors for base styles. Use IDs sparingly, mainly for JavaScript hooks. Avoid inline styles entirely.

This keeps specificity manageable. High specificity makes CSS harder to override and maintain.

It's like a chain of command. A direct order from the CEO (ID) overrides a department policy (class), which overrides a company-wide guideline (element selector).

Real-World Example: Putting It All Together

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>CSS Selectors Demo</title>
  <style>
    /* Element selector: base styles */
    body {
      font-family: Arial, sans-serif;
      line-height: 1.6;
    }

    /* Group selector: all headings */
    h1, h2, h3 {
      color: darkblue;
    }

    /* Class selector: reusable component */
    .card {
      border: 1px solid #ddd;
      padding: 20px;
      margin: 20px 0;
    }

    .highlight {
      background-color: yellow;
    }

    /* ID selector: unique element */
    #main-header {
      background-color: navy;
      color: white;
      padding: 20px;
      text-align: center;
    }

    /* Descendant selector: scoped styling */
    .card h2 {
      margin-top: 0;
    }

    .card p {
      color: #666;
    }
  </style>
</head>
<body>
  <header id="main-header">
    <h1>My Website</h1>
  </header>

  <div class="card">
    <h2>First Card</h2>
    <p>This is the first card content.</p>
    <p class="highlight">This paragraph is highlighted.</p>
  </div>

  <div class="card">
    <h2>Second Card</h2>
    <p>This is the second card content.</p>
  </div>
</body>
</html>

This example shows:

  • Element selector (body) for base styles

  • Group selector (h1, h2, h3) for consistent heading colors

  • Class selectors (.card, .highlight) for reusable components

  • ID selector (#main-header) for unique header

  • Descendant selectors (.card h2, .card p) for scoped styling

Common Beginner Mistakes

Forgetting the Dot for Classes

/* WRONG */
card {
  border: 1px solid black;
}

/* CORRECT */
.card {
  border: 1px solid black;
}

Without the dot, CSS thinks you're targeting an element called card, not a class.

Forgetting the Hash for IDs

/* WRONG */
header {
  background: navy;
}

/* CORRECT */
#header {
  background: navy;
}

Using Same ID Multiple Times

<!-- WRONG -->
<div id="box">Box 1</div>
<div id="box">Box 2</div>

<!-- CORRECT -->
<div class="box">Box 1</div>
<div class="box">Box 2</div>

No Space in Descendant Selectors

/* Descendant selector: span inside div */
div span {
  color: red;
}

/* Different: div that also has class span (rare) */
div.span {
  color: blue;
}

The space matters.

The Takeaway

CSS selectors are how you choose which HTML elements to style. Element selectors target all elements of a type. Class selectors target elements with a specific class (reusable). ID selectors target one unique element (use sparingly). Group selectors apply styles to multiple different selectors. Descendant selectors target elements inside other elements. Specificity determines which rule wins when multiple rules apply (ID beats class beats element).

In 90% of cases, you'll use class selectors. They're flexible, reusable, and keep specificity manageable. Start with element selectors for base styles, use classes for everything else, and save IDs for JavaScript or truly unique elements.

Master selectors and you've mastered the foundation of CSS. Everything else is just learning which properties to apply.

More from this blog