通过使用 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 类应用到单个元素?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号