How to apply CSS style to the different elements having the same class name in HTML?



HTML classes are global attributes that are used by HTML tags to specify a list of classes that are case-sensitive in nature. These classes are then used by CSS, to apply styling to that particular tag that has the class, and by Javascript, to manipulate the HTML element’s behavior, interactivity, or styles.

Approach 1; Using the dot(.) selector

In this approach, we will simply use the dot (.) selector to select multiple elements having the same class names, and apply the same set of styles to them using CSS.

Example

In this example, we will select a “p” tag and a “span” HTML tag using their class, and give them a text color “red” using CSS.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>How to apply CSS style to the different elements having the same class name in HTML?</title>
   <style>
      .sample {
         color: red;
      }
   </style>
</head>
<body>
   <p class="sample">This is p tag content!</p>
   <span class="sample">This is span tag content!</span>
</body>
</html>

Approach 2: Using “p” tage and “span” HTML tag

In this approach, we will apply a different set of styles to the elements that have the same class names using CSS. For this, we will use the HTML tag name, followed by the dot (.) selector to select a particular element and give the desired CSS styles to it.

Example

In this example, we will select a “p” tag and a “span” HTML tag using their class, and give them a different text color using CSS.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>How to apply CSS style to the different elements having the same class name in HTML?</title>
   <style>
      p.sample {
         color: red;
      }
      span.sample {
         color: green;
      }
   </style>
</head>
<body>
   <p class="sample">This is p tag content!</p>
   <span class="sample">This is span tag content!</span>
</body>
</html>

Conclusion

In this article, we learned about how to select HTML elements from their class names, and how to apply the same as well as different CSS styles to them, using 2 different approaches. In the first approach, we used the dot (.) selector to select multiple elements having the same class names, and applied the same styles to them, In the second approach, we used an HTML tag name followed by the dot (.) selector to apply different CSS styles to elements having the same class names.


Advertisements