HTML class Attribute

Definition and Usage

class This attribute specifies the class name (classname) of the element.

class The attribute is mainly used to point to the class (class) in the stylesheet. However, it can also be used to change HTML elements with specified class through JavaScript (HTML DOM).

See also:

HTML Tutorial:HTML attributes

CSS Tutorial:CSS Syntax

CSS Reference Manual:CSS .class selector

HTML DOM Reference Manual:HTML DOM getElementsByClassName() Method

HTML DOM Reference Manual:HTML DOM className Property

HTML DOM Reference Manual:HTML DOM classList Property

HTML DOM Reference Manual:HTML DOM Style object

Instance

Example 1

Use the class attribute in an HTML document:

<html>
<head>
<style>
h1.intro {
  color: blue;
}
p.important {
  color: green;
}
</style>
</head>
<body>
<h1 class="intro">Header 1</h1>
<p>A paragraph.</p>
<p class="important">Please note, this is an important paragraph. :)</p>
</body>
</html>

Try It Yourself

More examples are provided below the page.

Syntax

<element class="classname">

Attribute value

Value Description
classname

Specify one or more class names for an element.

If you want to specify multiple classes, you can separate class names with spaces.

This allows you to combine multiple CSS classes for an HTML element.

For example: <span class="left important">

Naming rules:

  • Must start with a letter A-Z or a-z
  • Can be followed by: letters (A-Za-z), numbers (0-9), hyphens ("-"), and underscores ("_").

More examples

Example 2

Add multiple classes to an HTML element:

<!DOCTYPE html>
<html>
<head>
<style>
h1.intro {
  color: blue;
  text-align: center;
}
.important {
  background-color: yellow;
}
</style>
</head>
<body>
<h1 class="intro important">Title 1</h1>
<p>A paragraph.</p>
</body>
</html>

Try It Yourself

Example 3

Use JavaScript to add a yellow background color to the first element with class="example" (index 0).

let x = document.getElementsByClassName("example");
x[0].style.backgroundColor = "yellow";

Try It Yourself

Example 4

Use JavaScript to add the "mystyle" class to the element with id "myDIV":

document.getElementById("myDIV").classList.add("mystyle");

Try It Yourself

Browser Support

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
Support Support Support Support Support