
A CSS selector tells the browser which elements a rule applies to. You can match an element by type, class, ID, or by how it relates to other elements.
3. CSS selectors
3.1. Universal selector
* matches every element. For example, * { box-sizing: border-box; } sets a consistent box model for elements on the page.
3.2. Type selector
Use an element name. p { color: green; } matches every paragraph.
3.3. Class selector
A period introduces a class. .highlight { color: red; } matches elements whose class attribute contains highlight. An element can have several classes. If two ordinary class rules set the same property with equal precedence and specificity, the rule that appears later in the stylesheet wins. The order of class names in the HTML makes no difference.
3.4. ID selector
A hash introduces an ID. #summary { color: blue; } targets the element with id="summary". Use each ID only once per document.
3.5. Descendant combinator
A space represents any depth of nesting. div p matches paragraphs anywhere inside a div, including inside another nested element.
3.6. Selector lists and combined conditions
A comma lists alternatives. div, p matches any div or paragraph. Join conditions without spaces when they must apply to the same element. p.highlight matches a paragraph with that class, and .highlight.featured requires both classes.
3.7. Child combinator
div > p matches paragraphs whose immediate parent is a div. A paragraph inside a section within that div is a descendant of the div and a child of the section.
3.8. Next-sibling combinator
div + p matches a paragraph immediately after a div when both have the same parent. A second paragraph next to it does not match that selector.
3.9. Selector reference
| Selector | Matches |
|---|---|
* | Every element |
p | All paragraph elements |
.class | Elements with that class |
#id | An element with that ID |
a b | Elements matching b anywhere inside a |
.first.second | Elements carrying both classes |
p.first | Paragraphs carrying the class first |
a, b | Elements matching either selector |
a > b | Elements matching b whose direct parent matches a |
a + b | Elements matching b immediately after a sibling matching a |
3.10. Examples
p { background-color: grey; } /* Type */
.highlight { color: red; } /* Class */
#summary { color: green; } /* ID */
* { font-style: italic; } /* Universal */
p a { background-color: orange; } /* Descendant */
h3, small { color: blue; } /* Selector list */
div > span { color: purple; } /* Child */
span + small { background: yellow; } /* Next sibling */Explore the original examples in CodePen, then see the lesson on attribute selectors.
Try it yourself
Which selector matches only links immediately inside an element with the class menu?
Show the answer
.menu > a. To include links nested inside lists or other containers, use .menu a.