HTML Classes and Id
The class and id attributes give elements names, so CSS and JavaScript can find them.
The class Attribute
A class can be used by many elements. In CSS, you select a class with a dot (.) and the class name.
Example
<!DOCTYPE html>
<html>
<head>
<style>
.city {
background-color: #1e3a8a;
color: white;
padding: 10px;
margin-bottom: 8px;
}
</style>
</head>
<body>
<div class="city"><h2>Karachi</h2><p>The largest city of Pakistan.</p></div>
<div class="city"><h2>Lahore</h2><p>Famous for its food and gardens.</p></div>
<div class="city"><h2>Quetta</h2><p>Known for fruit and cool weather.</p></div>
</body>
</html>Try it Yourself »One CSS rule styles all three boxes. Change the rule once and every box changes.
Many Classes on One Element
An element can have several classes, separated by spaces.
Example
<!DOCTYPE html>
<html>
<head>
<style>
.badge { padding: 4px 10px; border-radius: 12px; color: white; }
.green { background-color: green; }
.red { background-color: crimson; }
</style>
</head>
<body>
<p>Ali: <span class="badge green">Paid</span></p>
<p>Ayesha: <span class="badge red">Pending</span></p>
</body>
</html>Try it Yourself »The id Attribute
An id must be unique: only one element on the page can have a given id. In CSS, you select an id with a hash (#).
Example
<!DOCTYPE html>
<html>
<head>
<style>
#main-title {
color: #e34c26;
text-align: center;
}
</style>
</head>
<body>
<h1 id="main-title">Workownix Results</h1>
<p>Congratulations to all students!</p>
</body>
</html>Try it Yourself »id with JavaScript and Links
JavaScript often uses an id to find one exact element. Links can also jump to it with #id.
Example
<!DOCTYPE html>
<html>
<body>
<p id="message">Click the button.</p>
<button onclick="document.getElementById('message').innerHTML = 'Hello, Ayesha!'">Say hello</button>
</body>
</html>Try it Yourself »Hello, Ayesha!
class vs id
| class | id | |
|---|---|---|
| How many elements? | Many | Only one per page |
| CSS selector | .name | #name |
| Typical use | Shared styles | One special element, links, JavaScript |
Naming Rules
- Names are case sensitive:
Cardandcardare different. - An id cannot contain spaces. (A space in
classmeans two classes.) - Use clear names like
price-boxormain-menu, notbox1.
Use classes for styling in most cases. Keep ids for elements that are truly unique, like a page section you link to.
Exercise
Exercise
How do you select an element with class="card" in CSS?
