DEV Community

sanjeev singh
sanjeev singh

Posted on

CSS Selectors 101: Targeting Elements with Precision

You've written your HTML. You've got a heading, a few paragraphs, some buttons. Now you want to make it look good. You open your CSS file and you write:

p {
  color: blue;
}
Enter fullscreen mode Exit fullscreen mode

And suddenly — every single paragraph on the page turns blue. Every one of them. But you only wanted to style that one paragraph near the top. The one that says "Welcome."

How do you tell CSS, "No, not all of them. Just that one"?

That's exactly what selectors solve. They're how CSS targets specific elements on a page. And once you understand them, you'll have precise control over exactly what gets styled and what doesn't.

How do we tell CSS which elements to style — and how specific can we get?

Let's find out.


1. Why CSS Selectors Are Needed

CSS works by attaching styles to elements. But a webpage can have hundreds of elements — dozens of paragraphs, multiple headings, countless divs. If every style rule applied to everything, webpages would be a mess.

Selectors solve this problem. A selector is the part of a CSS rule that says which element(s) should receive the style.

Every CSS rule has two parts:

selector {
  property: value;
}
Enter fullscreen mode Exit fullscreen mode

The selector is the targeting system. The property: value is the style being applied. This entire article is about that first part — the selector.

Analogy: Imagine you're a teacher with a classroom of 30 students. You don't want to shout the same instruction at everyone every time. Sometimes you call on one specific student by name. Sometimes you address the whole row. Sometimes you say "everyone wearing a red shirt." Selectors work the same way — they let you choose who you're talking to.


2. The Element Selector

The simplest selector is the element selector. You just type the name of an HTML element, and CSS styles every element of that type on the page.

How It Works

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

p {
  color: gray;
  line-height: 1.6;
}
Enter fullscreen mode Exit fullscreen mode

That h1 selector targets every <h1> on the page. That p selector targets every <p>.

Seeing It in Action

HTML:                                   CSS:
─────                                   ───
<h1>My Website</h1>                     h1 { color: darkblue; }
<p>Welcome to my site.</p>              p  { color: gray; }
<p>Here is some more text.</p>

Result:
────────────────────────────────────────
  My Website                ← darkblue (matched by h1)
  Welcome to my site.       ← gray     (matched by p)
  Here is some more text.   ← gray     (matched by p)
────────────────────────────────────────
Enter fullscreen mode Exit fullscreen mode

Both paragraphs turn gray because the p selector matches all of them.

Analogy: The element selector is like saying "everyone in this room." It doesn't care about names or labels — it just catches every element of that type.


3. The Class Selector

The element selector is useful, but it's not precise enough when you need to style only some elements of a type. That's where the class selector comes in.

A class is a reusable label you attach to any HTML element using the class attribute. Then in CSS, you target that label with a dot . in front of it.

How It Works

<p>This is a regular paragraph.</p>
<p class="highlight">This one is special.</p>
<p>This is another regular paragraph.</p>
Enter fullscreen mode Exit fullscreen mode
p {
  color: gray;
}

.highlight {
  color: red;
  font-weight: bold;
}
Enter fullscreen mode Exit fullscreen mode

The .highlight selector targets only the paragraph that has class="highlight". The others stay gray.

Seeing It in Action

HTML Elements:                          Which selector matches?
──────────────                          ──────────────────────
<p>                                     p        → gray
<p class="highlight">                   p + .highlight → red, bold
<p>                                     p        → gray

Result:
────────────────────────────────────────
  This is a regular paragraph.          ← gray
  This one is special.                  ← red + bold
  This is another regular paragraph.    ← gray
────────────────────────────────────────
Enter fullscreen mode Exit fullscreen mode

Why Classes Are So Powerful

Classes are reusable. You can apply the same class to completely different elements:

<h2 class="highlight">A Heading</h2>
<p class="highlight">A Paragraph</p>
<div class="highlight">A Div</div>
Enter fullscreen mode Exit fullscreen mode

All three get the .highlight styles, even though they're different element types. This is one of the most important ideas in CSS.

Analogy: A class is like a colored name tag. You can hand out the same red name tag to anyone in the room — it doesn't matter if they're sitting in the front row or the back. Everyone wearing that red tag gets the same treatment.


4. The ID Selector

The ID selector works similarly to the class selector, but with one critical difference: an ID must be unique on the page. There can only be one element with a given ID.

In HTML, you set an ID with the id attribute. In CSS, you target it with a # in front of the name.

How It Works

<h1 id="main-title">Welcome</h1>
<h1>Another Heading</h1>
Enter fullscreen mode Exit fullscreen mode
h1 {
  color: gray;
}

#main-title {
  color: darkgreen;
  font-size: 48px;
}
Enter fullscreen mode Exit fullscreen mode

Only the heading with id="main-title" gets the green color and larger size. The other <h1> stays gray.

Seeing It in Action

HTML Elements:                          Which selector matches?
──────────────                          ──────────────────────
<h1 id="main-title">                    h1 + #main-title → darkgreen, 48px
<h1>                                    h1               → gray

Result:
────────────────────────────────────────
  Welcome                               ← darkgreen, large (ID match)
  Another Heading                       ← gray (element match only)
────────────────────────────────────────
Enter fullscreen mode Exit fullscreen mode

Class vs ID — What's the Difference?

This is one of the most common beginner questions, so let's lay it out clearly:

                  Class (.name)           ID (#name)
                  ─────────────           ──────────
Can you reuse it? Yes — as many times     No — must be unique
                  as you want             on the page

How to write it   class="card"            id="main-title"
in HTML?

How to target     .card                   #main-title
it in CSS?

When to use it?   Styling a group of      Styling one specific,
                  similar elements        unique element

Priority?         Lower                   Higher (we'll cover
                                          this in section 7)
Enter fullscreen mode Exit fullscreen mode

Analogy: A class is like a job title — multiple people can be "Designer." An ID is like a social security number — it belongs to exactly one person and no one else.


5. Group Selectors

Sometimes you want to apply the exact same styles to several different elements at once. You could write the same block of CSS three times. But that's repetitive and hard to maintain.

The group selector solves this. You simply list the selectors you want, separated by commas.

How It Works

h1, h2, h3 {
  color: darkblue;
  font-family: Georgia, serif;
}
Enter fullscreen mode Exit fullscreen mode

That single rule styles <h1>, <h2>, and <h3> — all three at once.

Seeing It in Action

Without group selector:                 With group selector:
───────────────────────                 ────────────────────
h1 {                                    h1, h2, h3 {
  color: darkblue;                        color: darkblue;
  font-family: Georgia, serif;            font-family: Georgia, serif;
}                                       }
h2 {
  color: darkblue;                      ← Same result. One-third the code.
  font-family: Georgia, serif;
}
h3 {
  color: darkblue;
  font-family: Georgia, serif;
}
Enter fullscreen mode Exit fullscreen mode

You can also mix element selectors, class selectors, and ID selectors in a group:

h1, .intro, #banner {
  margin-bottom: 20px;
}
Enter fullscreen mode Exit fullscreen mode

Analogy: A group selector is like calling out multiple names at once — "Sarah, James, and Priya, come to the front." One instruction. Multiple targets.


6. Descendant Selectors

Now we're getting into the really useful stuff. A descendant selector lets you target an element only when it's inside another specific element.

You write it by putting a space between two selectors. The element on the left is the ancestor. The element on the right is the one being styled — but only when it lives inside that ancestor.

How It Works

<div class="card">
  <p>I am inside the card.</p>
</div>

<p>I am outside the card.</p>
Enter fullscreen mode Exit fullscreen mode
p {
  color: gray;
}

.card p {
  color: darkgreen;
  font-weight: bold;
}
Enter fullscreen mode Exit fullscreen mode

The .card p selector says: "Find a <p> that is inside an element with class card." Only that paragraph turns green. The one outside stays gray.

Seeing It in Action

HTML Structure:
────────────────────────────────────────
  <div class="card">
    <p>I am inside the card.</p>       ← matched by .card p
  </div>

  <p>I am outside the card.</p>        ← matched by p only
────────────────────────────────────────

Targeting Flow:
────────────────────────────────────────
  .card p

    .card    →  Find an element with class "card"
      p      →  Then find a <p> INSIDE it
                (anywhere inside, at any depth)
────────────────────────────────────────

Result:
────────────────────────────────────────
  I am inside the card.                 ← darkgreen, bold
  I am outside the card.                ← gray
────────────────────────────────────────
Enter fullscreen mode Exit fullscreen mode

Why This Matters

Descendant selectors let you style elements contextually. The same <p> tag can look completely different depending on where it lives on the page:

.sidebar p    { font-size: 14px; color: #666; }
.main-content p { font-size: 16px; color: #333; }
.footer p     { font-size: 12px; color: #999; }
Enter fullscreen mode Exit fullscreen mode

Three different styles. All targeting <p>. All based on where that paragraph lives.

Analogy: A descendant selector is like saying "find all the chairs inside the library." Not every chair on campus — just the ones inside that specific room. The ancestor sets the context; the descendant is what you're actually targeting.


7. Selector Priority (The Basics)

Here's a question that comes up a lot: what happens when two selectors try to style the same element differently? Which one wins?

CSS has a built-in ranking system called specificity. The more specific your selector, the higher it ranks — and the more likely its styles are to win.

Here's the basic priority order, from lowest to highest:

Priority    Selector Type       Example
────────    ─────────────────   ─────────────────
Lowest      Element selector    p
  │         Class selector      .highlight
  │         ID selector         #main-title
Highest     ↑                   ↑
Enter fullscreen mode Exit fullscreen mode

Seeing It in Action

<p class="intro" id="opening">Hello, World!</p>
Enter fullscreen mode Exit fullscreen mode
p {
  color: gray;          /* Element selector — lowest priority */
}

.intro {
  color: blue;          /* Class selector — medium priority */
}

#opening {
  color: red;           /* ID selector — highest priority */
}
Enter fullscreen mode Exit fullscreen mode

All three selectors match the same paragraph. But the ID selector wins because it has the highest priority.

Result:
────────────────────────────────────────
  Hello, World!                         ← red (ID wins)
────────────────────────────────────────

Why?
  p          →  matches ✓   priority: low
  .intro     →  matches ✓   priority: medium
  #opening   →  matches ✓   priority: high  ← WINNER
────────────────────────────────────────
Enter fullscreen mode Exit fullscreen mode

The Simple Rule to Remember

  ┌────────────────────────────────────┐
  │  More specific = higher priority   │
  │                                    │
  │  Element  <  Class  <  ID          │
  │  (low)      (medium)   (high)      │
  └────────────────────────────────────┘
Enter fullscreen mode Exit fullscreen mode

Analogy: Think of it like authority at work. A general instruction from the company ("all employees wear name tags") can be overridden by a department rule ("engineers wear blue badges"), which can be overridden by a direct manager order ("you specifically — wear this badge today"). The more targeted the instruction, the more authority it carries.


Top comments (0)