CSS Selectors
Target elements with type, class, attribute, and pseudo selectors
Overview
Selectors determine which elements receive styles. Specificity and cascade decide which rule wins when multiple selectors match. Prefer classes over deep descendant chains for maintainability.
Syntax / Usage
/* Type */
p { line-height: 1.6; }
/* Class */
.btn-primary { background: blue; }
/* ID (use sparingly) */
#main { max-width: 1200px; }
/* Descendant and child */
.card p { color: #333; }
.nav > li { list-style: none; }
/* Attribute */
input[type="email"] { border-color: teal; }
/* Pseudo-classes */
a:hover { text-decoration: underline; }
li:first-child { font-weight: bold; }
input:focus-visible { outline: 2px solid blue; }
/* Pseudo-elements */
::placeholder { color: #999; }
p::first-line { font-variant: small-caps; }
Examples
Accessible focus styles:
:focus-visible {
outline: 2px solid var(--color-focus);
outline-offset: 2px;
}
State variants without JavaScript:
.toggle:checked + .label { color: green; }
Common Mistakes
- Overly specific selectors (
div.nav ul li a) hard to override - Relying on
!importantinstead of fixing specificity - Styling by ID across components—blocks reuse
- Universal selector
*reset hurting performance when overused
See Also
box-model custom-properties flexbox responsive-design