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 -
Use class attributes -
<div class="class1 class2">This element has two CSS classes applied to it</div>
Using JavaScript −
Given that there is a p tag with the id 'paragraph', we want to apply these classes -
<script> const paragraph = document.getElementById('paragraph'); paragraph.classList.add('one'); paragraph.classList.add('two'); </script>
<!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>
Save the above code in a file with a .html extension.
Open the file in a web browser.
The above is the detailed content of How to apply two CSS classes to a single element?. For more information, please follow other related articles on the PHP Chinese website!