CSS selectors target HTML elements for styling. Here's a comprehensive guide from basic to advanced.
Basic Selectors#
Attribute Selectors#
Combinators#
Pseudo-Classes#
Structural Pseudo-Classes#
Negation and Matching#
Pseudo-Elements#
Target and Focus#
State and Language#
Specificity#
Practical Examples#
Best Practices#
Selector Choice:
✓ Use classes for styling
✓ Use BEM or similar methodology
✓ Keep specificity low
✓ Prefer :where() for resets
Performance:
✓ Avoid deep nesting
✓ Avoid universal with descendants
✓ Use efficient selectors
✓ ID is fastest (but avoid for styling)
Maintainability:
✓ Be specific as needed
✓ Document complex selectors
✓ Use :is() to reduce repetition
✓ Keep selectors readable
Avoid:
✗ Over-qualified selectors (div.class)
✗ Deep descendant chains
✗ !important battles
✗ ID selectors for styling
Conclusion#
CSS selectors range from simple type and class selectors to powerful pseudo-classes like :has() and :is(). Master attribute selectors for dynamic styling, structural pseudo-classes for patterns, and understand specificity to write maintainable CSS. Modern selectors like :has() enable parent selection, while :where() allows zero-specificity utility styles.