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?

王林
Release: 2023-09-16 18:33:03
forward
1101 people have browsed it

如何将两个 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>
Copy after login
  • 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>
Copy after login

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>
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template