CSS How to apply two CSS classes to one element

CSS How to Apply Two CSS Classes to an Element

We can apply multiple CSS classes to an element by using the class attribute and separating each class with a space.

Methods

There are two ways to apply two CSS classes to an element, namely:

  • Using the class attribute
<div class="class1 class2">This element has two CSS classes applied to it</div> 
  • Using JavaScript –

Given there’s a p tag with the id ‘paragraph’, we want to apply a class to it –


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

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> <p id = 'paragraph'>Using JavaScript</p>
<script>
const paragraph = document.getElementById('paragraph');
paragraph.classList.add('one');
paragraph.classList.add('two');
</script>

</body>
</html>

Instructions

  • Save the above code in a file with a .html extension.

  • Open the file in a web browser.

Leave a Reply

Your email address will not be published. Required fields are marked *