ThiselementhastwoCSSclassesappliedtoit using JavaScript − Given that there is a p tag with the id 'paragraph', we Want to apply these classes -

Home >Web Front-end >CSS Tutorial >How to apply two CSS classes to a single element?

How to apply two CSS classes to a single element?

王林
王林forward
2023-09-16 18:33:031114browse

如何将两个 CSS 类应用到单个元素?

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

method

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>

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>

illustrate

  • 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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete