CSS selectors
A selector is the part of a CSS rule before the curly braces: it picks the elements the styles apply to.
Syntax
selector {
property: value;
}
h1, h2 { … } /* group */
.card > p { … } /* child */ Selector types
| Selector | What it does |
|---|---|
* | universal: every element |
p | by tag: every paragraph |
.card | by class: elements with class="card" |
#main | by id: the element with id="main" (one per page) |
[type="email"] | by attribute and its value |
a:hover | pseudo-class, a state: a link under the pointer |
p::first-line | pseudo-element, a part of an element: the first line of a paragraph |
.card p | a descendant at any depth |
.card > p | a direct child only |
h1 + p | the sibling right after |
h1 ~ p | all following siblings |
h1, h2 | a group: several selectors separated by commas |
Example
* { box-sizing: border-box; }
p { margin: 4px 0; }
.card {
padding: 12px;
border: 1px solid #94a3b8;
}
.card > p { color: #0284c7; }
h1 + p { font-weight: bold; }
a:hover { color: #dc2626; }
[data-state="new"] { background: #fef3c7; } <div class="card" data-state="new">
<h1>Card</h1>
<p>First paragraph after h1: bold (h1 + p) and blue (.card > p).</p>
<p>Second paragraph: blue only.</p>
<div><p>Nested deeper: not blue, it is not a direct child of .card.</p></div>
<a href="#top">Hover over me</a>
</div> Result
Good to know
- When several rules set the same property, the more specific one wins: a style attribute → #id → .class, [attribute], :pseudo-class → tag. With equal specificity, the one lower in the CSS wins.
- Classes are more convenient for styling: ids are very specific and hard to override later.
- A selector reads right to left: .card p means "any p inside .card".
Sources and specification
- MDN: CSS selectors — MDN Web Docs
- Selectors Level 4 (W3C) — W3C
See also
The :nth-child() pseudo-class
The CSS :nth-child() pseudo-class selects elements by position among siblings: odd and even, 3n, 3n+1, -n+3 for the first three, and :nth-of-type.
The color property
The CSS color property sets the text color: color names, hex, rgb() and hsl(), transparency and currentColor, inheritance and contrast for accessibility.
The class attribute
The global class attribute, used for CSS styling and for querySelector selection.
The id attribute
The global id attribute uniquely identifies an element within a document.
Linking CSS
Lesson 11: three ways to add CSS — an external file via <link rel="stylesheet">, a <style> block in head and the style attribute. Example and task.