Topic 2 of 30
Selectors
Overview
CSS selectors specify which HTML elements a rule applies to. Mastering selectors lets you style elements precisely without adding unnecessary classes, keeping your HTML clean.
Syntax
css
/* Element */ p { }
/* Class */ .card { }
/* ID */ #hero { }
/* Universal */ * { }
/* Descendant */ nav a { }
/* Child */ ul > li { }
/* Adjacent */ h1 + p { }
/* Sibling */ h1 ~ p { }
/* Attribute */ input[type="email"] { }
/* Pseudo-class */ a:hover { }
/* Pseudo-element */p::first-line { }
/* Grouping */ h1, h2, h3 { }Common Pitfalls
- Avoid over-reliance on ID selectors (#id) — they have extremely high specificity and override almost everything.
- The universal selector (*) matches ALL elements — use it only for resets and with caution.
- Interview tip: Specificity order: !important > inline > ID > class/pseudo-class/attribute > element > *
Real-World Example
Styling a navigation menu with various selectors:
example
css
/* Style all nav links */
nav a {
color: #fff;
text-decoration: none;
padding: 8px 16px;
}
/* Only direct children list items */
nav > ul > li {
display: inline-block;
}
/* Active link */
nav a.active {
color: #FFD700;
border-bottom: 2px solid #FFD700;
}
/* Input focus state */
input[type="search"]:focus {
outline: 2px solid #FFD700;
border-color: transparent;
}
/* First paragraph after a heading */
h2 + p {
font-size: 1.1rem;
color: #aaa;
}