Episode 24 of 53
Combining Selectors in CSS
Learn how to combine different types of CSS selectors for precise targeting.
You can combine multiple selector types to create very precise and powerful rules.
Chaining Selectors
Write selectors together (no space) to combine conditions:
/* An element that is both a <p> AND has class "intro" */
p.intro {
font-size: 1.2rem;
color: #555;
}
/* A <div> with both classes "card" and "featured" */
div.card.featured {
border: 2px solid gold;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}
/* An <input> with type "text" and class "large" */
input.large[type="text"] {
font-size: 1.25rem;
padding: 0.75rem;
}
Combining with Combinators
/* A .highlight paragraph that's a direct child of .article */
.article > p.highlight {
background: #fff3cd;
padding: 1rem;
border-left: 4px solid #ffc107;
}
/* The first .card after an h2 inside .section */
.section h2 + .card {
margin-top: 0;
}
Combining with Pseudo-Classes
/* The first li with class "item" */
li.item:first-child {
font-weight: bold;
}
/* Hover state on nav links */
nav a.active:hover {
color: #e74c3c;
}
Best Practices
- Keep selectors readable — don't over-combine
- Higher specificity makes overriding harder
- Aim for the minimum specificity needed to achieve your goal