在 HTML 中为一个元素使用多个 CSS 类

front end technologyhtmlweb development更新于 2025/4/4 11:56:17

为了更快地创建 CSS,我们可以为单个 HTML 元素赋予多个类,并为每个类分别设置样式。这种方法使我们能够管理样式应用冗余。我们可以将通用样式应用于多个类,也可以将特定类的样式应用于特定类。

语法

<tag_name class="class_1 class_2">

示例

在下面的示例中,我们对两个段落都使用了类"Varma"的样式,而将第二个类 varma1 的样式应用于第二个段落。

<!DOCTYPE html> <html> <style> .varma { font-size: larger; margin-bottom: 35px; background-color: lightgreen; } .varma1 { color: red; } </style> <body> <p class="varma"> Hello Everyone. </p> <p class="varma varma1"> Welcome to Turorialspoint. </p> </body> </html>

执行后,上述脚本将生成结果。该结果为:文本"welcome to tutorialspoint"与两种 CSS 样式相结合,以及文本"hello everyone"与单一 CSS 相结合。

示例:使用 JavaScript

在下面的示例中,我们通过声明 .bg-blue 样式和 .text-white 样式,为单个文本添加两种样式。

<!DOCTYPE html> <html> <style> .bg-blue { background-color: lightgreen; } .text-white { color: red; } </style> <body> <div id="varma">Welcome To Tutorialspoint</div> <script> const box = document.getElementById('varma'); box.classList.add('bg-blue', 'text-white'); </script> </body> </html>

执行时,脚本生成一个应用了两个 CSS 的文本"welcome to tutorialspoint"输出。


相关文章


有用资源