A selector chooses which HTML elements a rule styles.
| Selector | Example | Selects |
|---|---|---|
| Element | p |
all <p> elements |
| Class | .note |
elements with class="note" |
| ID | #header |
the element with id="header" |
| Universal | * |
every element |
| Group | h1, h2 |
all h1 and h2 |
| Descendant | nav a |
links inside nav |
| Child | ul > li |
li that are direct children of ul |
| Attribute | input[type="text"] |
text inputs |
Class vs ID
A class can be used on many elements. An ID must be unique on the page.
Example
Example — Common selectors
HTML
<style>
p { color: #333; }
.note { background: #fff7d6; padding: 8px; }
#title { color: #1f386b; }
ul > li { color: green; }
</style>
<h2 id="title">Selectors</h2>
<p>Normal paragraph.</p>
<p class="note">Paragraph with class note.</p>
<ul>
<li>Direct child item</li>
</ul>