How to use CSS selectors efficiently
· Category: HTML & CSS
Short answer
Efficient CSS selectors target elements with minimal complexity, favor classes over deeply nested selectors, and use pseudo-classes and combinators to express state and relationships.
Steps
- Prefer class selectors (
.btn) over element or ID selectors for reusable styles. - Use combinators (
>,+,~) to express parent-child or sibling relationships without excessive nesting. - Leverage pseudo-classes (
:hover,:focus-visible,:nth-child) for state-based styling. - Use attribute selectors (
[type="checkbox"]) when class hooks are not available.
Example
/* Direct child */
.nav > li { display: inline-block; }
/* Adjacent sibling */
input:checked + label { font-weight: bold; }
/* Attribute selector */
input[type="email"] { border-color: blue; }
/* Pseudo-class */
button:focus-visible {
outline: 3px solid orange;
}
Tips
- Avoid selectors deeper than three levels; they are hard to override and slow to match.
- Use
:is()and:where()to reduce repetition and specificity. - Be cautious with universal selectors (
*) in large documents.