
通过使用 class 属性并用空格分隔每个类,我们可以将多个 CSS 类应用于单个元素。
方法
有两种方法可以将两个 CSS 类应用到单个元素 -
使用类属性 -
<div class="class1 class2">This element has two CSS classes applied to it</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 的文件中。
在网络浏览器中打开文件。










