HTML Class Attribute

Written by

Aayushi Bansal

Sometimes, rather than uniquely identifying one element within a document, we sometimes require a way to identify several elements as being different from the other elements on the page.

For example, we might have some words or sentences that contain information that is more important than others and want to distinguish these elements. To do this we can use the class attribute.

Every HTML element can have a class attribute. Its value should describe the class it belongs to. 

HTML classes are used to define the equal styles for multiple elements having the same class name. The <div> elements are used to point to the same class name.

The styling of HTML elements using classes is done using CSS.

In CSS, the classes are called by using the dot operator (.) followed by the name of the class.

For example:


.effects {

Background-color: light-blue;

color: black;}



<p class=”effects”> The body will have background color of blue and text color black.</p>


Note:  Different tags can share the same class and hence has same style.


<h1 class=”effects”>heading</h1>

<p class=”effects”>paragragh</p>


Multiple classes:

The elements can have more than one class name and these class names are separated by a space.

For example:

<p class=”effects alignment”>the paragraph will be styled by two classes named as effects which adds effects to the paragraph and alignment which align the paragraph to right, left or center.</p>


Class attribute on inline elements:


<!DOCTYPE html>
span.important {
  font-size: 140%;
  color: black;

text-transform: underline; } </style> </head> <body> <h1>My <span class="important">Important</span> Heading</h1> <p>This is some <span class="important">important</span> text.</p> </body>



Similar to the id attribute, the class attribute is also used in javascript to perform certain tasks by elements with specified class name. Javascript can access elements with specified class using getElementByClass() method.

Note: There is another attribute called id which is very similar to the class attribute but the difference lies in the fact that the id for each HTML element should be unique whereas a single class name can be used by multiple HTML elements.


HTML Class Attribute