Skip to main content

Command Palette

Search for a command to run...

CSS Selectors 101: Targeting Elements with Precision

Master the Art of Selecting and Styling HTML Elements Effortlessly

Published
2 min readView as Markdown
CSS Selectors 101: Targeting Elements with Precision
T

MERN Stack developer focused on building real-world web applications. Currently exploring Generative AI and modern backend practices. I write about what I learn, build, and break along the way.

1. Why CSS Selectors Are Needed

Imagine you are in a classroom and you say:

“Everyone, stand up.”

All students stand up.

Now you say:

“Only boys, stand up.”

Only a specific group stands up.

This is exactly what CSS selectors do.

Your webpage has many HTML elements.
CSS needs a way to choose which elements to style.

That’s why selectors exist.
They are simply rules to select elements.

2. Element Selector

This is the simplest selector.

You directly select an HTML tag.

p {
  color: blue;
}

This means:
“Style all <p> elements.”

Like saying:
“All students, listen.”

3. Class Selector

Sometimes you don’t want to style everything.
Only some elements.

That’s where class comes in.

.box {
  border: 2px solid black;
}
<div class="box">Hello</div>
<div class="box">World</div>

This means:
“Style only elements with class box.”

Like saying:
“Only students wearing blue shirts.”

4. ID Selector

ID is for one unique element.

#main {
  background: yellow;
}
<div id="main">Main Section</div>

This means:
“Style only this one element.”

Like saying:
“Only Rohit, stand up.”

5. Group Selectors

You can select multiple things together.

h1, p, div {
  font-family: Arial;
}

Means:
“Apply same style to all of them.”

Like saying:
“Boys and girls, come here.”

6. Descendant Selectors

This selects elements inside other elements.

div p {
  color: red;
}

Means:
“Only <p> inside <div>.”

Like saying:
“Students inside this classroom.”

7. Basic Selector Priority (High Level)

Sometimes multiple selectors target same element.

Which one wins?

Priority (simple):

ID > Class > Element

Example:

p { color: blue; }
.text { color: green; }
#title { color: red; }

This will be red, because ID wins.

Final Thought

CSS selectors are the foundation of CSS.
If you understand selectors, you control the page.

No selectors → no styling.
Selectors are how CSS sees your HTML.

Web from Zero: HTML & CSS for Real Developers

Part 4 of 4

In this series, I teach HTML and CSS from zero, focusing on how browsers render pages, how layouts work, and how real websites are built not just how to write tags and styles.

Start from the beginning

Understanding HTML Tags and Elements

The building blocks of the web, made easy