English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

HTML Reference Manual

HTML Tag Reference

HTML class attribute

The value of the global attribute class is a list of element class names (classes) separated by spaces, which allows CSS and JavaScript to select and access specific elements through class selectors (class selectors) or DOM methods (document.getElementsByClassName).

HTML Global Attributes

Online Example

Use the class attribute in an HTML document:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>基础教程网(oldtoolbag.com)</title>
<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">Note that this is an important paragraph. :)</p>
</body>
</html>

Test to see ‹/›

Although there are no requirements for the naming of class, web developers are best to use names that express the semantic purpose of the element rather than the name that describes the element's display (even if an element is italic, the class name should not be italics). Semantic naming remains logical even when the page display changes.

Browser Compatibility

IEFirefoxOperaChromeSafari

All major browsers support the class attribute

Definition and Usage

The class attribute defines the class name of an element.

The class attribute assigns one or more class names to an element.

The class attribute is typically used to point to a stylesheet class. However, JavaScript can also use it (via HTML DOM) to change HTML elements with specified classes.

HTML 4.01 with HTML5differences

In HTML5 In, the class attribute can be used for any HTML element (it will Validate any HTML element. But it may not be useful).

In HTML 4.01 In, the class attribute cannot be used for: <base>, <head>, <html>, <meta>, <param>, <script>, <style>, and <title>.

Syntax

    <element>

Attribute value

ValueDescription
classnameSpecify the class name of the element. To specify multiple classes for an element, separate the class names with spaces. <span>. HTML elements allow the use of multiple classes.

Name rules:

  • Must start with a letter A-Z or a-z at the beginning

  • Can be the following characters: (A-Za-, and number (0-9, dash ("-")-, and underscore ("_")

  • In HTML, class names are case-sensitive

More examples

Add multiple classes to an element
How to add multiple classes in HTML elements.

HTML Global Attributes