The class and id attributes are the bridges between HTML and CSS (and JavaScript). They let you target specific elements without changing the HTML structure.
class attributeA class can be applied to many elements and one element can have many classes:
<div class="card">First card</div>
<div class="card">Second card</div>
<div class="card featured">Featured card (two classes!)</div>
In CSS, target a class with .:
.card {
border: 1px solid #ccc;
padding: 1rem;
}
.featured {
background-color: gold;
}
Classes make it easy to apply consistent styling to groups of related elements.
id attributeAn id must be unique — no two elements on the same page should share an id:
<header id="site-header">...</header>
<main id="main-content">...</main>
<footer id="site-footer">...</footer>
In CSS, target an id with #:
#site-header {
background-color: #333;
color: white;
}
id values also serve as scroll anchors — perfect for table-of-contents navigation:
<!-- Navigation -->
<nav>
<a href="#intro">Introduction</a>
<a href="#features">Features</a>
<a href="#contact">Contact</a>
</nav>
<!-- Sections -->
<section id="intro"><h2>Introduction</h2></section>
<section id="features"><h2>Features</h2></section>
<section id="contact"><h2>Contact</h2></section>
class | id | |
|---|---|---|
| Uniqueness | Reusable | Must be unique |
| CSS selector | .classname | #idname |
| Multiple per element | Yes | Only one id per element |
| Use for | Styling groups | Unique landmarks, anchors |
Build a one-page portfolio skeleton:
<nav> with three anchor links: #about, #projects, #contact.<section> elements, each with the matching id.<div class="card"> inside it.class="card highlight").Apply multiple classes with a space: class="card featured large"