如何對一個元素應用兩個 CSS 類?
我們可以透過使用 class 屬性並用空格分隔每個類來對單個元素應用多個 CSS 類。有兩種方法可以將兩個 CSS 類應用於單個元素 -
使用 Class 屬性應用兩個類
用於設定單個類的 class 屬性也可用於設定多個類 -
<div class="class1 class2">This element has two CSS classes applied to it</div>
示例
讓我們看這個例子 -
<!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> </body> </html>
使用 JavaScript 應用兩個類
給定一個具有 id ‘paragraph’ 的 p 標籤,我們想對其應用這些類。classList 是一個屬性,add() 方法用於新增類。在這種情況下,我們添加了兩個類,即 one 和 two -
<script> const paragraph = document.getElementById('paragraph'); paragraph.classList.add('one'); paragraph.classList.add('two'); </script>
以下是 .one 和 .two 的樣式 -
<style> .one { color: blue; } .two { font-size: 20px; } </style>
示例
讓我們看這個例子 -
<!DOCTYPE html> <html> <head> <title>Multiple Classes</title> <style> .one { color: blue; } .two { font-size: 20px; } </style> </head> <body> <p id = 'paragraph'>Demo content</p> <script> const paragraph = document.getElementById('paragraph'); paragraph.classList.add('one'); paragraph.classList.add('two'); </script> </body> </html>
廣告