CSS Selectors: Precision targeting for DOM Elements
CSS is useless without elements to style. Selectors are the hooks you use to grab parts of your HTML structure to paint them with properties. Master them, and you control the layout.
1. The Basics: Tags, Classes, and IDs
The foundation of CSS targeting relies on three primary selectors:
- Tag Selectors: Target the raw HTML element. Using
p { color: red; }targets every single paragraph on the page. - Class Selectors (.): Reusable targets. You can add
class="btn"to multiple different elements. In CSS, target it with a dot:.btn. - ID Selectors (#): Unique targets. An ID can only appear ONCE per page. In CSS, target it with a hash:
#header.
2. Combinators: Hunting Relationships
Elements on a web page are structured like a family tree. You can target elements based on their ancestors or siblings using combinators:
Descendant (Space): div p selects any <p> that lives inside a <div>, regardless of how deep it is.
Child (>): ul > li strictly targets direct children. An li inside another nested list wouldn't be affected.
3. The Specificity Wars
When two CSS rules target the exact same element with conflicting properties (e.g., one says blue, another says red), who wins? The answer is Specificity.
[Inline Styles] > [ID Selectors] > [Classes, Attributes, Pseudo-classes] > [HTML Tags]
View Architecture Tip+
Avoid over-qualifying your selectors! Instead of writing div#main-content ul.list li.item a.link, just write .link. Keep your specificity low to make your CSS easier to override and maintain later (e.g., BEM methodology).
❓ Frequently Asked Questions
When should I use an ID vs a Class?
Class (.): Use it for 99% of your styles. They're reusable and keep specificity manageable.
ID (#): Reserve them almost exclusively for JavaScript anchor links or unique absolute structural layouts. Their high specificity makes them a nightmare to override in modular CSS.
What does the universal selector (*) do?
The asterisk * selects literally everything on the page. It's commonly used in CSS resets to remove default margins and paddings.
* { box-sizing: border-box; margin: 0; padding: 0; }What happens if I use !important?
It breaks the cascade rules and forces itself to apply, regardless of specificity. It's considered a "bad practice" unless you're overriding styles from an external library (like Bootstrap) that you can't modify otherwise.
