HTML Tutorial menu

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

html
<!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

html
<!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

html
<!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 »

JavaScript often uses an id to find one exact element. Links can also jump to it with #id.

Example

html
<!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 »
Output
Hello, Ayesha!

class vs id

classid
How many elements?ManyOnly one per page
CSS selector.name#name
Typical useShared stylesOne special element, links, JavaScript

Naming Rules

  • Names are case sensitive: Card and card are different.
  • An id cannot contain spaces. (A space in class means two classes.)
  • Use clear names like price-box or main-menu, not box1.

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?

Learn HTML with a teacher

Join the Web Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp