通过使用 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 的文件中。
在网络浏览器中打开文件。
以上就是如何将两个 CSS 类应用到单个元素?的详细内容,更多请关注www.92cms.cn其它相关文章!






