What is Class Attribute?
In HTML, the 'class attribute' is used to assign one or more class names to an HTML element. CSS and JavaScript can target a group of HTML elements with the same class name to apply styles or define behaviors. In other words, it allows you to style and multiple HTML elements with the same class name using CSS and JavaScript.
To add a class attribute in an HTML element, you need to add class="your-class-name" in the openning tag of an HTML element.
Example of Adding Class Name
In the following example, we have a paragraph (<p>) element with a class name 'test' at the openning tag as class="test"
. Here class is the HTML class attribute and "test" is the class name value. "test" can be used to target and apply CSS style to the paragraph element.
Example of HTML Class Name
Example of Adding Class in Internal CSS Style Element
In the following example, we have added HTML <style> tag between the <head> and </head> tag; it is known as internal CSS style. Inside the style element, we have added CSS class name test
. To define a class name in CSS style period/full-stop (.)
sign must be put before the class name as shown in the following example. color
and font-size
CSS properties have been set in the class. Color has been set to red and font size has been set to 18px.
Example of Adding Class in CSS Style Element
Output of the above example
You can use HTML class as selector in style element within head element to apply CSS style.