Why We Need Selectors
To style or manipulate specific elements with CSS or JavaScript, you first need a way to target them. The class and id attributes are the two most common hooks for this.
class and id
<div id="main-banner" class="banner highlight">
Welcome to DevAcademy!
</div>class vs id
| class | id | |
|---|---|---|
| Uniqueness | Can be reused on many elements | Must be unique on the page |
| Multiple values | Yes, space-separated | No, only one value |
| CSS selector | .classname | #idname |
| Typical use | Reusable styling | Unique anchors, JS hooks, ARIA references |
Selecting in CSS
<style>
.highlight {
background: yellow;
}
#main-banner {
font-size: 1.5rem;
}
</style>Multiple Classes
An element can have several classes separated by spaces. This lets you compose small, reusable style rules instead of writing one large class per component.
Multiple Classes Example
<button class="btn btn-primary btn-large">Sign Up</button>Using id as an Anchor
Besides styling, id is commonly used as a target for same-page links (<a href="#section">) and as a hook for JavaScript’s document.getElementById().
Duplicate IDs Are Invalid
Using the same id value on more than one element in a page is invalid HTML. It can cause CSS to apply inconsistently and break JavaScript methods that expect a single match.
Best Practice
Default to class for styling since it’s reusable across many elements. Use id sparingly — only when you need a guaranteed single, unique reference.