HTML Classes

The HTML class attribute is used to define a class for an HTML element.

The HTML class attribute is used to define a single or multiple class names for an HTML element.

 These class name can be used by CSS and JavaScript to do some custom tasks for HTML elements. 

We can use this class in CSS with a specific class, write a period (.) character inside html element starting tags.

How it used ?

  • A class attribute can be defined within <style> tag
  • separate file using the (.) character.

Defining an HTML class

For creating the HTML class we firstly define style for HTML class using <style> tag inside the <head> section.

Example :

<head>  
    <style>  
        .river{   
            color: blue;  
            font-family: monospace;  
            background-color: aliceblue;
        }  
    </style>  
</head>

Understand the syntax of HTML Classes.

<tag class="className"> content </tag>  

1st Example of HTML Class

<!DOCTYPE html>  
<html>  
<head>  
    <style>  
        .river{   
            color: blue;  
            font-family: monospace;  
            background-color: aliceblue; 
        }  
    </style>  
</head> 
<body>  
<h1 class="river">Ganga</h1>  
<h2 class="river">Yamuna</h2>  
<h3 class="river">Saraswati</h3>  
<h4 class="river">Kaveri</h4>
</body>  
</html>
  Try it Yourself

2nd Example Using Another Class :

​​​​​​​Let's use a class name "Country" with CSS to style all elements.

<style>    
.country{    
    background-color: orange;    
    color: white;    
    padding: 10px;    
}     
</style>    
    
<h2 class="country">India</h2>    
<p>India Mottos is Truth alone triumphs.</p>    
    
<h2 class="country">Nepal</h2>    
<p>Nepal Mottos is Mother and motherland are greater than heaven.</p>    
    
<h2 class="country">South Africa</h2>    
<p>South Africa Mottos is Diverse people unite or Unity in Diversity.</p>
  Try it Yourself

3rd Example of Using Multiple Classes.

<style>    
.country{    
    background-color: orange;    
    color: white;    
    padding: 10px;    
}
.india{
    border:solid green 3px;
}
</style>
  <h2 class="country india">India</h2>    
  <p>India Mottos is Truth alone triumphs.</p>    

  <h2 class="country">Nepal</h2>    
  <p>Nepal Mottos is Mother and motherland are greater than heaven.</p>    

  <h2 class="country">South Africa</h2>    
  <p>South Africa Mottos is Diverse people unite or Unity in Diversity.</p>
  Try it Yourself

Using class Attribute in JavaScript

These class name used by JavaScript to do some custom tasks for HTML elements. 

JavaScript can access elements with a specific class name with the getElementsByClassName() method and we applied custom tasks on this element.

Example :

<script>
function myFunction() {
  var x = document.getElementsByClassName("country");
  for (var i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
}
</script>
  Try it Yourself