CSS Selectors Introduction
Master CSS selectors to target HTML elements precisely.
By EMEPublished: February 20, 2025
cssselectorsstylingspecificity
A Simple Analogy
CSS selectors are like finding people in a crowd. You can pick by name (class), ID, appearance (element), or relationships.
Why Selectors?
- Targeting: Apply styles to specific elements
- Efficiency: Avoid inline styles
- Maintainability: Change styles centrally
- Performance: Optimize with specific selectors
- Flexibility: Target any element
Basic Selectors
/* Element selector */
p { color: blue; }
/* Class selector */
.highlight { background: yellow; }
/* ID selector */
#main { font-size: 24px; }
/* Attribute selector */
input[type="text"] { border: 1px solid blue; }
/* Attribute value selector */
a[href*="example.com"] { color: green; }
Combinators
/* Descendant (space) */
div p { color: red; }
/* Child (>) */
ul > li { list-style: none; }
/* Adjacent sibling (+) */
h1 + p { margin-top: 0; }
/* General sibling (~) */
p ~ p { margin-top: 16px; }
Pseudo-Classes
a:hover { color: red; }
input:focus { border: 2px solid blue; }
li:first-child { font-weight: bold; }
li:last-child { border-bottom: none; }
p:nth-child(odd) { background: #f0f0f0; }
Best Practices
- Specificity: Use lowest needed
- Performance: Avoid deep nesting
- Reusability: Use classes for styles
- Clarity: Name classes semantically
- Avoid !important: Use specificity instead
Related Concepts
- CSS specificity
- CSS cascade
- CSS Grid
- Flexbox
Summary
Use CSS selectors to target elements precisely. Master combinators, pseudo-classes, and attribute selectors.