Smal SEO Tool

HTML Class Attribute

The class attribute is used to specify one or more class names for an HTML element.

Using the Class Attribute

The class attribute is often used to point to a class name in a style sheet. It can also be used by JavaScript to access and manipulate elements with the specific class name.

Example: Styling Elements with the Same Class

In this example, two <h2> elements with class="city" are styled equally.

html
<!DOCTYPE html>
<html>
<head>
<style>
.city {
  background-color: tomato;
  color: white;
  padding: 10px;
}
</style>
</head>
<body>

<h2 class="city">London</h2>
<p>London is the capital of England.</p>

<h2 class="city">Paris</h2>
<p>Paris is the capital of France.</p>

</body>
</html>
Try it Yourself »

Multiple Classes

HTML elements can belong to more than one class. To specify multiple classes, separate the class names with a space, e.g. <p class="main important">. The element will get the styles from all the specified classes.

Example: Using Multiple Classes

The first <h2> element belongs to both the `city` and `main` classes, and will get styles from both.

html
<!DOCTYPE html>
<html>
<head>
<style>
.city {
  background-color: tomato;
  color: white;
  padding: 20px;
}

.main {
  text-align: center;
}
</style>
</head>
<body>

<h2 class="city main">London</h2>
<h2 class="city">Paris</h2>
<h2 class="city">Tokyo</h2>

</body>
</html>
Try it Yourself »

Different Elements Can Share Same Class

Different HTML elements can point to the same class name. Here, both <h1> and <p> have elements with the class "note", and they will share the same style.

Example: Different Elements, Same Class

html
<!DOCTYPE html>
<html>
<head>
<style>
.note {
  font-size: 120%;
  color: red;
}
</style>
</head>
<body>

<h1>My <span class="note">Important</span> Heading</h1>
<p>This is some <span class="note">important</span> text.</p>

</body>
</html>
Try it Yourself »

Test Yourself with an Exercise

How do you specify multiple classes for one element?