CSS Selectors 101: Targeting Elements with Precision
1. Why CSS selectors are needed
CSS selectors answer one simple question:
Without selectors, CSS wouldn’t know where to apply styles.
Selectors let you:
Target specific elements
Style multiple elements at once
Avoid repeating the same CSS again and again
2. Element selector
The element selector targets all elements of a given type.
Example:
p {
color: blue;
}
3. Class selector
Class selectors are used when you want to style specific elements, not all.
Class selector uses a dot (.).
HTML:
<p class="note">Important text</p>
CSS:
.note {
color: red;
}
4. ID selector
ID selectors target one unique element.
ID selector uses a hash (#).
HTML:
<h1 id="title">Welcome</h1>
CSS:
#title {
color: green;
}
5. Group selectors
Group selectors let you apply the same style to multiple selectors.
Example:
h1, h2, p {
font-family: Arial;
}
6. Descendant selectors
Descendant selectors target elements inside other elements.
Example:
div p {
color: purple;
}
This means:
Style all
<p>elements inside a<div>
It does not affect paragraphs outside the div.
7. Basic selector priority (very high level)
When multiple styles apply to the same element, priority matters.
At a very high level:
ID selector > Class selector > Element selector
Example:
#boxbeats.box.boxbeatsdiv