在 HTML 中, id
和class
是允許您將樣式或腳本套用到網頁上特定元素的屬性。以下是如何使用它們的範例:
id
: id
屬性用於唯一標識頁面上的 HTML 元素。每id
值在文件中必須是唯一的。您可以將id
用於樣式目的或透過 JavaScript 定位特定元素。
html <!DOCTYPE html>
<html>
<head>
<style>
#uniqueElement {
color: blue;
font-weight: bold;
}
</style>
</head>
<body>
<p id="uniqueElement">This is a unique element with an ID.</p>
<p>This is another paragraph.</p>
</body>
</html>
在此範例中,第一個<p>
(段落)元素的id
屬性設定為「uniqueElement」。關聯的 CSS 樣式僅套用於具有該特定id
的元素。
class
: class
屬性用於對元素進行分類,並將樣式或腳本套用至共用相同類別的多個元素。
html <!DOCTYPE html>
<html>
<head>
<style>
.highlight {
background-color: yellow;
}
.italic {
font-style: italic;
}
</style>
</head>
<body>
<p class="highlight">This paragraph has a highlight class.</p>
<p>This is a regular paragraph.</p>
<p class="highlight italic">This paragraph has both highlight and italic classes.</p>
</body>
</html>
在此範例中, class
屬性用於建立兩個 CSS 類別:「highlight」和「italic」。這些類別可以套用於一個或多個 HTML 元素以相應地設定它們的樣式。
請記住,您可以在一個元素上同時使用id
和class
。 id
必須是唯一的,而多個元素可以共享相同的class
。這是結合兩者的範例:
html <!DOCTYPE html>
<html>
<head>
<style>
#uniqueElement {
color: blue;
font-weight: bold;
}
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<p id="uniqueElement" class="highlight">This is a unique element with an ID and a highlight class.</p>
<p class="highlight">This paragraph has a highlight class.</p>
</body>
</html>
在此範例中,具有id
「uniqueElement」的元素具有獨特的樣式,並且它還具有用於附加樣式的「highlight」類別。