HTML Classes

HTML Class Attribute:

For elements with the same class name, the HTML class attribute defines equal styles.
Example:

<!DOCTYPE html>
<html>
<head>
<style>
.fruits {
  background-color: crimson;
  color: white;
  margin: 15px;
  padding: 10px;
}
</style>
</head>
<body>
<div class="fruits">
<h2>Apple</h2>
</div> 
 
<div class="fruits">
<h2>Mango</h2>
</div>
<div class="fruits">
<h2>Orange</h2>
</div>
</body>
</html>

Explanation:

In the above example. All the div elements belong to the same class.

Class Attribute in Javascript:

The getElementsByClassName() method can be used to access elements with a specified class name by Javascript.
Example:

<!DOCTYPE html>
<html>
<body>
<h1 class="name">Tom</h1>
<h1 class="name">Jerry</h1>
<button onclick="Function()">Hide elements</button>
<script>
function Function() {
  var f = document.getElementsByClassName("name");
  for (var x = 0; x < f.length; x++) {
    f[x].style.display = "none";
  }
}
</script>
</body>
</html>

Explanation:

In the above example, we used the getElementsByClassName() method to hide all elements of the same class name.

Multiple Classes:

Multiple class names for HTML elements must be separated by a space.
Example:

<!DOCTYPE html>
<html>
<style>
.flowers {
  background-color: crimson;
  color: white;
  padding: 20px;
} 
.first {
  text-align: center;
}
</style>
<body>
<h2 class="flowers first">Rose</h2>
<h2 class="flowers">Tulip</h2>
<h2 class="flowers">Orchid</h2>
</body>
</html>

Explanation:
In the above example, we used two classes “flowers” and “first” for a single HTML element.


Different Tags for the same Class:

When we want to share the same style among different HTML tags (<h1>, <h2>, p, etc.), all the tags should have the same class name.

Example:

<!DOCTYPE html>
<html>
<style>
.flowers {
  background-color: crimson;
  color: white;
  padding: 20px;
} 
</style>
<body>
<h1 class="flowers">Rose</h2>
<p class="flowers">Rose is my favourite flower.</p>
</body>
</html>

Explanation:
In the above example, we used the same class name for different tags to apply the same style to all.