CSS Selectors
What are selectors?
A CSS selector tells the browser which elements to apply styles to. Mastering selectors is one of the most important CSS skills because everything else — colors, layout, animation — depends on targeting the right elements.
Basic selectors
Element selector — targets all elements of a type:
CSS
p {
color: #333;
}Class selector — targets elements with a specific class (prefix with
.):HTML
<p class="highlight">Important text</p>CSS
.highlight {
background-color: #fef3c7;
padding: 0.5rem;
}ID selector — targets one specific element (prefix with
#):CSS
#main-title {
font-size: 2.5rem;
}Use classes for styling, not IDs. IDs should be reserved for JavaScript or anchor links.
Combining selectors
Descendant — selects elements inside another:
CSS
article p {
line-height: 1.8;
}This targets every
<p> inside an <article>, no matter how deeply nested.Direct child — uses
>:CSS
nav > a {
text-decoration: none;
}This only targets
<a> elements that are direct children of <nav>.Multiple selectors — comma-separated:
CSS
h1, h2, h3 {
font-family: Georgia, serif;
}Pseudo-classes
Pseudo-classes target elements in a specific state:
CSS
a:hover {
color: #dc2626;
}
input:focus {
outline: 2px solid #2563eb;
}
li:first-child {
font-weight: bold;
}Specificity — which rule wins?
When multiple rules target the same element, specificity decides the winner:
- Inline styles (
style="...") — highest specificity - ID selectors (
#name) — high - Class selectors (
.name) — medium - Element selectors (
p) — lowest
CSS
p { color: black; } /* specificity: 0-0-1 */
.intro { color: blue; } /* specificity: 0-1-0 — wins over element */
#hero { color: red; } /* specificity: 1-0-0 — wins over class */When specificity is equal, the last rule in the stylesheet wins. This is the "cascading" part of CSS.
Key takeaway
Use class selectors for almost everything. Learn how specificity works so you don't end up fighting your own CSS with
!important hacks.