HTML class attribute

HTML class attribute: It defines one (or) more class names for HTML element. While the class name can be used by CSS and JavaScript for performing certain tasks with a specified class name. And this attribute can be used by any HTML element.

HTML class attribute

This attribute is mainly to print the class in a style sheet. And it can also be used by JavaScript via HTML DOM for making changes to HTML elements. And the class attribute can be used by all the elements.

Syntax: <element class=”classname”>

Supported Browsers

This attribute will be supported by different types of browsers. They are as  follows:

  • Chrome
  • Mozilla
  • Opera
  • Safari
  • Internet Explorer

Example:

<!DOCTYPE html> 
<html> 
<head> 
<style> 
.country { 
    background-color: black; 
    color: white; 
    padding: 8px; 
} 
</style> 
</head> 
  
<body> 
  
<h2 class = "country">CHINA</h2> 
<p>China has the largest population in the world.</p> 
  
<h2 class = "country">INDIA</h2> 
<p>India has the second largest population in the world.</p> 
  
<h2 class = "country">UNITED STATES</h2> 
<p>United States has the third largest population in the world.</p> 
  
</body> 
</html>

Output:

HTML class attribute

Example: Using multiple classes

HTML elements can have more than one class name, where each class name must be separated by a space.

<!DOCTYPE html> 
<html> 
<style> 
.country { 
background-color: green; 
color: white; 
padding: 10px; 
} 

.middle { 
text-align: center; 
} 
</style> 

<body> 
  <h1><center> Freshersnow  </center></h1>
<h2 class = "country middle">INDIA</h2> 
<h2 class = "country">AUSTRILA</h2> 
<h2 class = "country">UNITED STATES</h2> 

</body> 
</html> 

Output:

HTML class attribute