通过使用 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 类应用到单个元素?的详细内容。