Skip to main content

Command Palette

Search for a command to run...

CSS Selectors 101: Targeting Elements with Precision

Published
2 min read

HTML gives structure to a webpage, but without CSS, everything looks plain and boring.

Now here’s the real challenge:

How do we tell CSS which HTML elements to style?

We don’t want to style everything the same way.

We want precision.

That’s where CSS selectors come in.

Why CSS Selectors Are Needed 🎯

CSS selectors allow you to:

Choose specific HTML elements

Apply styles only where needed

Avoid unnecessary styling conflicts

📌 In simple words:

Selectors help CSS “find” elements inside HTML.

🧒 Analogy:

Selectors are like calling someone by name in a crowded room.

Element Selector 🧱

The element selector targets all elements of a specific tag.

Example:

p {

color: blue;

}

📌 This styles all <p> tags on the page.

🧒 Think of it as:

“Style everyone who is a paragraph.”

Class Selector 🏷️

The class selector targets elements with a specific class.

Syntax:

.className {

property: value;

}

Example:

.card {

border: 1px solid black;

}

<div class="card">Content</div>

📌 Multiple elements can share the same class.

🧒 Like giving multiple people the same team badge.

ID Selector 🆔

The ID selector targets one unique element.

Syntax:

Css

#idName {

property: value;

}

Example:

Css

#mainTitle {

font-size: 32px;

}

Html

<h1 id="mainTitle">Hello</h1>

📌 IDs should be unique — only one per page.

🧒 Like calling someone by their unique roll number.

Group Selectors 👥

Group selectors allow you to style multiple elements at once.

Example:

Css

h1, h2, p {

color: green;

}

📌 This applies the same style to all listed elements.

🧒 Like sending one message to multiple people.

Descendant Selectors 🌳

Descendant selectors target elements inside other elements.

Example:

Css

div p {

color: red;

}

📌 This styles only <p> tags inside <div>, not all paragraphs.

🧒 Like saying:

“Only paragraphs inside this container.”

Basic Selector Priority (Very High Level) 🧠

Sometimes multiple selectors target the same element.

So who wins?

Priority Order (Simple):

ID selector (#id)

Class selector (.class)

Element selector (p, div)

📌 More specific selector = higher priority.

Conclusion 🎯

CSS selectors are not complicated — they are tools for precision.

Element selectors style broadly

Class selectors give flexibility

ID selectors give uniqueness

Descendant selectors give control