The HTML class
Attribute is used in HTML to specify the class of an HTML element. This allows developers to group together elements that have similar properties, and then apply styles and behavior to them using CSS or JavaScript.
To use the class
attribute, you first need to define a class in your CSS stylesheet. This is done by specifying the class name preceded by a period .
and then defining the styles that should be applied to that class.
For example, suppose you want to apply a background color to a group of elements with the class name my-class
. You could define this class in your CSS stylesheet as follows:
.my-class {
background-color: yellow;
}
Then, in your HTML document, you can apply the class to any element by adding the class
attribute with the name of the class as the attribute value:
<p class="my-class">This paragraph will have a yellow background color.</p>
<div class="my-class">This div will also have a yellow background color.</div>
Both the paragraph and the div will have a yellow background color because they both have the my-class
class applied to them.
You can also apply multiple classes to an element by separating them with a space in the class
attribute:
<p class="my-class other-class">This paragraph will have both the my-class and other-class styles applied to it.</p>
In this example, the my-class
and other-class
styles will both be applied to the paragraph element.