The HTML <class> attribute is used to specify a class for an HTML element. Multiple HTML elements can share the same class. The <class> attribute is often used to point to a class name in a style sheet. It can also be used by a JavaScript to access and manipulate elemetns with the specific class name. In the following example we have three <div> elements with a <class> attribute with the value of "city". All of the three <div> elements will be styled equally according to the <.city> style definition in the head section:
London is the capital of England.
Paris is the capital of France.
Tokyo is the capital of Japan.
In the following example we have two <span> elements with a <class> attribute with the value of "note". Both <span> elements will be styled equally according to the <.note> style definition in the head section:
This is some important text.
The <class> attribute can be used on any HTML element. The class name is case sensitive! To create a class; write a period (.) character, followed by a class name. Then, define the CSS properties within curly braces {}:
Use CSS to style elements with the name "city"
London is the capital of England.
Paris is the capital of France.
Tokyo is the capital of Japan.
Here, all three h2 elements belongs to the "city" class. In addition, London also belongs to the "main" class, which center-aligns the text.
Different HTML elements can point to the same class name. In the following example, both <h2> and <p> point to the "city" class and will share the same style:
Click the button to hide all elements with the class name "city":
The class name can also be used by JavaScript to perform certain tasks for specific elements. JavaScript can access elements with a specific class name with the <getElementsByClassName()> method:
London is the capital of England.
Paris is the capital of France.
Tokyo is the capital of Japan