How to apply two CSS classes to a single element?


We can apply multiple CSS classes to a single element by using the class attribute and separating each class with a space. There are two ways to apply two CSS classes to a single element −

Apply two Classes Using the Class Attribute

The class attribute that is used to set a single class can also be used to set multiple classes −

<div class="class1 class2">This element has two CSS classes applied to it</div>

Example

Let us see the example −

<!DOCTYPE html>
<html>
<head>
   <title>Multiple Classes</title>
   <style>
      .one {
         color: red;
      }
      .two {
         font-size: 24px;
      }
   </style>
</head>
<body>
   <p class = "one two">Using Class Attribute</p>
</body>
</html>

Apply two Classes Using JavaScript

Given that there is a p tag with id ‘paragraph’ to which we want to apply the classes. The classList is a property and the add() method is used to add a class. In this case, we have added two classes i.e. one and two −

<script>
   const paragraph = document.getElementById('paragraph');
   paragraph.classList.add('one');
   paragraph.classList.add('two');
</script>

The following are the .one and .two styles −

<style>
   .one {
      color: blue;
   }
   .two {
      font-size: 20px;
   }
</style>

Example

Let us see the example −

<!DOCTYPE html>
<html>
<head>
   <title>Multiple Classes</title>
   <style>
      .one {
         color: blue;
      }
      .two {
         font-size: 20px;
      }
   </style>
</head>
<body>
   <p id = 'paragraph'>Demo content</p>
   <script>
      const paragraph = document.getElementById('paragraph');
      paragraph.classList.add('one');
      paragraph.classList.add('two');
   </script> 
</body>
</html>

Updated on: 16-Nov-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements