CSS Selectors 101 - Targeting Elements with Precision
Source: Dev.to
Introduction
Imagine someone builds your house perfectly… but they forget to paint it.
Without CSS, a website is just plain text and structure.
CSS (Cascading Style Sheets) lets you create beautiful, professional websites. Without it, even a site like Amazon would look plain and boring.
What is CSS?
- Cascading – styles flow step‑by‑step.
- Style – defines how something looks.
- Sheet – a file (usually
styles.css) that contains all your style rules.
Common CSS Selectors
Element Selector
Targets HTML elements by their tag name.
<p>This is a paragraph</p>
p {
color: red;
}
All <p> elements become red.
Class Selector
Uses the class attribute to style specific elements. The selector starts with a dot (.) and can be reused on multiple elements.
<p class="text-red">Great blog, like please!</p>
.text-red {
color: red;
}
ID Selector
Targets a single, unique element. The selector starts with a hash (#). An ID must be unique on the page and cannot start with a number.
<p id="first">Like it at least</p>
#first {
color: red;
}
Group Selector
Applies the same style to multiple selectors at once, reducing repetition.
h1 {
font-family: Verdana, sans-serif;
}
h2 {
font-family: Verdana, sans-serif;
}
/* Grouped version */
h1, h2 {
font-family: Verdana, sans-serif;
}
Descendant Selector
Selects elements that are inside another element (parent‑child relationship).
<div>
<p>Great blog</p>
</div>
div p {
color: red;
}
Only <p> elements that are descendants of a <div> are styled.
Selector Priority (Specificity)
When multiple rules match the same element, the one with higher specificity wins. From lowest to highest priority:
- Type selectors (e.g.,
p,div) - Class selectors (e.g.,
.box) - ID selectors (e.g.,
#header) - Inline styles (e.g., “) – override all other selectors.
Conclusion
CSS turns a simple webpage into a beautiful experience.
If HTML is the house, CSS is the paint, furniture, and decoration.
Happy styling! 🚀