Element, Class, and ID Selectors
8 min read
The Three Core Selectors
Every CSS rule starts with a selector. The three most fundamental types target elements by their tag name, their class attribute, or their id attribute.
css
/* Element selector — targets ALL <p> tags */
p {
margin-bottom: 1rem;
}
/* Class selector — targets elements with class="card" */
.card {
border: 1px solid #e2e8f0;
border-radius: 8px;
padding: 1rem;
}
/* ID selector — targets the ONE element with id="hero" */
#hero {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: #fff;
}Combining Selectors
You can apply the same declarations to multiple selectors by separating them with commas. You can also chain selectors to target elements that match all conditions simultaneously.
css
/* Comma — applies to both h1 and h2 */
h1, h2 {
font-family: 'Inter', sans-serif;
}
/* Chained — a <button> that also has class "primary" */
button.primary {
background: #6366f1;
color: #fff;
}Prefer classes over IDs for styling. IDs have much higher specificity and can only be used once per page, making your CSS harder to reuse.
Ready to test yourself?
Practice CSS— quiz & coding exercises