CSS Selectors
A selector tells CSS which HTML elements to style. Good use of selectors keeps your CSS short and clean.
Basic selectors
| Selector | Example | Selects |
|---|---|---|
| Element | p | All p elements |
| Class | .note | All elements with class="note" |
| ID | #header | The element with id="header" |
| Universal | * | All elements |
| Group | h1, h2, p | All the listed elements |
p { color: gray; } /* element */
.note { background: #fff3cd; } /* class */
#header { font-size: 28px; } /* id */
* { box-sizing: border-box; } /* universal */
h1, h2 { color: navy; } /* group */
Read the interview questions What is the CSS class selector? and What is grouping in CSS?
Combinators
| Selector | Example | Selects |
|---|---|---|
| Descendant (space) | div p | All p inside a div, at any depth |
| Child (>) | div > p | Only p that are direct children of a div |
| Adjacent sibling (+) | h2 + p | The first p right after an h2 |
| General sibling (~) | h2 ~ p | All p after an h2, with the same parent |
div p { color: green; }
div > p { font-weight: bold; }
h2 + p { font-size: 20px; }
What the rules above do
I am a direct child of div (bold and green).
I am inside a section in the div (green only).
Read the interview question What are child selectors?
Attribute selectors
a[target="_blank"] { color: red; } /* links that open in a new tab */
input[type="text"] { border: 1px solid gray; }
a[href^="https"] { color: green; } /* href starts with https */
a[href$=".pdf"] { color: purple; } /* href ends with .pdf */
Pseudo-classes and pseudo-elements
These select a state or a part of an element, like a:hover or p::first-line. See Pseudo-classes and pseudo-elements.
Summary
- Use element, class and id selectors for most work.
- Combinators select elements by their place in the HTML.
- Attribute selectors select by attributes.
- Next: CSS Specificity.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |