HTML class 属性用于为 HTML 元素指定单个或多个类名。CSS 和 JavaScript 可以使用类名来为 HTML 元素执行一些任务。您可以在具有特定类的 CSS 中使用此类,写一个句点 (.) 字符,后跟用于选择元素的类的名称。
类属性可以在 <style> 标签中定义,也可以在单独的文件中使用 (.) 字符定义。
在 HTML 文档中,我们可以对不同的元素使用相同的类属性名称。
<head>
<style>
.headings{
color: lightgreen;
font-family: cursive;
background-color: black; }
</style>
</head>我们已经为类名“headings”定义了样式,并且我们可以将这个类名用于我们想要提供此类样式的任何 HTML 元素。我们只需要遵循以下语法即可使用它。
<tag class="ghf"> content </tag>
让我们在 CSS 中使用类名“Fruit”来设置所有元素的样式。
在这里您可以看到,我们使用了带有 (.) 的类名“fruit”来使用其所有元素。
当用户单击按钮时,让我们隐藏所有类名为“fruit”的元素。
<style>
.fruit {
background-color: orange;
color: white;
padding: 10px;
}
</style>
<h2 class="fruit">Mango</h2>
<p>Mango is king of all fruits.</p>
<h2 class="fruit">Orange</h2>
<p>Oranges are full of Vitamin C.</p>
<h2 class="fruit">Apple</h2>
<p>An apple a day, keeps the Doctor away.</p>让我们用类名“fruit”和类名“center”来设计元素。
<!DOCTYPE html>
<html>
<body>
<h2>Class Attribute with JavaScript</h2>
<p>Click the button, to hide all elements with the class name "fruit", with JavaScript:</p>
<button onclick="myFunction()">Hide elements</button>
<h2 class="fruit">Mango</h2>
<p>Mango is king of all fruits.</p>
<h2 class="fruit">Orange</h2>
<p>Oranges are full of Vitamin C.</p>
<h2 class="fruit">Apple</h2>
<p>An apple a day, keeps the Doctor away.</p>
<script>
function myFunction() {
var x = document.getElementsByClassName("fruit");
for (var i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
}
</script>
</body>
</html>您可以看到第一个元素 <h2> 属于“fruit”类和“center”类。
<!DOCTYPE html>
<html>
<style>
.fruit {
background-color: orange;
color: white;
padding: 10px;
}
.center {
text-align: center;
}
</style>
<body>
<h2>Multiple Classes</h2>
<p>All three elements have the class name "fruit". In addition, Mango also have the class name "center", which center-aligns the text.</p>
<h2 class="fruit center">Mango</h2>
<h2 class="fruit">Orange</h2>
<h2 class="fruit">Apple</h2>
</body>
</html>| 元素 | Chrome | IE | Firefox | Safari | Opera |
|---|---|---|---|---|---|
| <id> | Yes | Yes | Yes | Yes | Yes |