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

cssweb developmentfront end technology更新于 2025/1/1 1:48:17

我们可以通过使用 class 属性并用空格分隔每个类,将多个 CSS 类应用于单个元素。

方法

将两个 CSS 类应用于单个元素有两种方法 -

  • 使用 class 属性 -

<div class="class1 class2">此元素应用了两个 CSS 类</div>
  • 使用 JavaScript -

假设有一个 ID 为"paragraph"的 p 标签,我们想要将这两个类应用于该标签 -

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

说明

  • 将以上代码保存到扩展名为 .html 的文件中。

  • 在网页浏览器中打开该文件。


相关文章


有用资源