HTML / HTML Attributes

HTML Class Attribute

Dec 12, 2022
2 min read
HTML class Attribute

Definition

The class global attribute specifies one or more class names for an HTML element.

Applicable Elements

The class attribute is a Global Attribute, meaning it can be used with all HTML Elements.

HTML Global class Attribute

The class global attribute specifies one or more class names for an HTML element. They are primarily used with CSS to link a CSS style to an element, but JavaScript can also target them.

Syntax

<div class="classname"></div>

Usage

  • The class attribute can specify one or more class names for an element.
  • Multiple class names can be added with a space used as a separator.

Values

HTML5 supports numbers as class attribute values, but CSS selectors have some rules.

A valid name should:

  • Start with a letter (a-z)(A-Z), an underscore (_), or a hyphen (-).
  • Contain after the first letter any number, letter, hyphen, or underscore.
  • Be at least two characters in length.
  • Not start with a digit, two hyphens, or a hyphen followed by a number.

Examples

The example shows a simple CSS demonstration showing singular and multiple class names on paragraph elements.

<style>
  .red {
    color: red;
  }
  .blue {
    color: blue;
  }
  .red.blue {
    color: purple;
  }
</style>

<p class="red">This text is red.</p>
<p class="blue">This text is blue.</p>
<p class="red blue">This text is purple</p>

Specification

The class HTML specification is as follows:

Browser Support

The class attribute has the following browser support:

Desktop

ChromeEdgeFirefoxIEOperaSafari
<class>YesYesYesYesYesYes

Mobile

Android WebviewChrome AndroidFirefox AndroidOpera AndroidiOS SafariSamsung Internet
<class>YesYesYesYesYesYes