CSS Selectors Explained (How CSS Knows What to Style)
I write technical articles for developers who already know the basics but want clarity. No hand-holding, no fluff — just structured explanations for people revisiting concepts or fixing confusion.
CSS doesn’t randomly apply styles.
It needs a way to choose elements on a page.
That’s exactly what CSS selectors are for.
Why CSS selectors are needed
Imagine shouting “Hey!” in a crowded room.
Everyone looks.
Selectors are how you address the exact person you want to talk to.
Without selectors, CSS wouldn’t know which element to style.
Element selector
This is the simplest selector.
It targets all elements of a given type.
Example:
p {
color: red;
}
This styles every <p> tag on the page.
Use this when you want broad styling.
Class selector
Class selectors target elements using a class name.
Example:
.card {
padding: 16px;
}
Classes are reusable.
Multiple elements can share the same class.
This is the most commonly used selector in real projects.
ID selector
ID selectors target one unique element.
Example:
#header {
background: black;
}
IDs should be unique on a page.
They have higher priority, so they’re used carefully.
Group selectors
Group selectors apply the same style to multiple selectors.
Example:
h1, h2, h3 {
font-family: sans-serif;
}
This avoids repeating the same CSS again and again.
Descendant selectors
These target elements inside other elements.
Example:
div p {
color: blue;
}
This means:
“Style <p> tags that are inside a <div>”.
Very useful for scoped styling.
Basic selector priority (very high level)
Not all selectors are equal.
At a high level:
ID selectors have highest priority
Class selectors come next
Element selectors have lowest priority
This decides which style wins when rules conflict.
Why selectors matter
Selectors are the foundation of CSS.
Even modern tools like Tailwind rely on the same idea:
choosing elements and applying styles.
Once you understand selectors, CSS feels way less random.