CSS Selectors
CSS selectors are patterns that pick elements out of the document so you can style them. The same property applied through different selectors will style different elements.
Common selector types
| Selector | Picks… | Example |
|---|---|---|
| Universal | Every element. | * { box-sizing: border-box; } |
| Type | All elements of a given tag name. | p { color: #333; } |
| Class | Elements with a matching class. | .btn { padding: 8px 14px; } |
| ID | The one element with that id. | #hero { height: 80vh; } |
| Attribute | Elements with a given attribute. | input[type="email"] { … } |
| Pseudo-class | Elements in a particular state. | a:hover { color: red; } |
| Pseudo-element | A part of an element. | p::first-letter { font-size: 2em; } |
| Grouping | Several selectors at once. | h1, h2, h3 { font-family: Inter; } |
Combinators
Combinators describe the relationship between two selectors:
Tip: Reach for classes for almost everything. IDs win specificity battles too easily and make styles hard to override.
Example
Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>
<h1>CSS Selectors</h1>
<div class="box">Edit the CSS on the left, then click Run »</div>
</body>
</html>
Try it Yourself »
Exercise
Target every element with class "card" and give it a white background.
{ background: #fff; }
Class selectors start with a dot.
Discussion
Loading…