Published Feb 24, 2023Updated Sep 23, 2023
Contribute to Docs

A class is an HTML attribute used to select one or more elements for CSS styling or JavaScript purposes.

For Styling

The class attribute is used for assigning styles to elements. Multiple classes can be assigned to a single element in a space-separated list. (e.g. class="class1 class2 class3")

Inside the stylesheet, a class name is selected with the following syntax:

.class-1 {

A class selector is a name preceded by a period (.).

Below is some markup with the classes header-1 and P1 and P2. Elements with the header-1, P1 and P2 class names receive different styling.

<!DOCTYPE html>
<html lang="en">
.header-1 {
background-color: lightblue;
font-size: 40px;
.P1 {
background-color: white;
font-size: 25px;
.P2 {
background-color: yellow;
font-size: 20px;
<div class="title">
<h1 class="header-1">PIZZA MAN</h1>
<p class="P1">
Pizza Man is a family-owned business since 1964. Our goal is to make the
best pizza and have it delivered to your place.
<p class="P2">We have 3 locations so far and growing.</p>

The code above will result in an output in a browser similar to:

Browser window with different text blocks formatted according to their class attribute

For JavaScript

The class attribute is used to perform JavaScript operations on HTML elements. Through the Document Object Model (“DOM”) there are various JavaScript methods built for selecting elements via their class.

Assuming the markup from the last example is linked to a JavaScript file:

const innerDiv = document.getElementsByClassName('header-1')[0];

The code above selects the first element of a given class, and prints its content to the console.


All contributors

Looking to contribute?

Learn HTML on Codecademy