What Selectors Do
A selector determines which HTML elements a rule applies to. CSS offers many kinds of selectors, from simple element names to precise attribute matching.
Basic Selector Types
| Selector | Example | Targets |
|---|---|---|
| Type | p | Every <p> element |
| Class | .highlight | Every element with class="highlight" |
| ID | #header | The single element with id="header" |
| Universal | * | Every element on the page |
| Attribute | [type="email"] | Every element with a matching attribute |
Type, Class, and ID Selectors
<style>
p {
color: #333;
}
.highlight {
background: yellow;
}
#main-title {
font-size: 28px;
}
</style>
<h1 id="main-title">Main Title</h1>
<p>Regular paragraph.</p>
<p class="highlight">Highlighted paragraph.</p>Attribute Selectors
Attribute selectors target elements based on the presence or value of an HTML attribute, useful for styling form inputs by type without adding extra classes.
Attribute Selectors Example
<style>
input[type="email"] {
border-color: steelblue;
}
a[target="_blank"] {
color: darkorange;
}
</style>
<input type="email" placeholder="you@example.com" />
<a href="https://example.com" target="_blank">External Link</a>Grouping Selectors
Multiple selectors can share the same declaration block by separating them with commas, avoiding repeated rules.
Grouped Selectors
<style>
h1, h2, h3 {
font-family: Georgia, serif;
color: #222;
}
</style>
<h1>Heading 1</h1>
<h2>Heading 2</h2>Class vs ID Selectors
Prefer class selectors for styling — they can be reused across many elements. Reserve ID selectors for unique, one-off cases, since an id must be unique per page and carries higher specificity that can be harder to override later.
Best Practice
Default to class selectors for anything reusable. Keep selectors as simple and flat as possible — deeply nested selectors become fragile and hard to override.