Skip to content

HTML 类(Classes)

的 class 属性允许你为一个 HTML 元素分配一个或多个类名(class name)。这主要用于通过 CSS 来定位(target)元素进行样式设置,或通过 JavaScript 进行操作(manipulation)。

你可以通过给多个元素相同的类名来应用相同的 CSS 样式。

设想一下如何为多个信息框设置一致的样式:

<div class="info-box">
<h2>London</h2>
<p>London is the capital city of England...</p>
</div>
<div class="info-box error">
<h2>System Alert</h2>
<p>An error occurred during the process.</p>
</div>
<div class="info-box success">
<h2>Update Complete</h2>
<p>Your profile has been updated successfully.</p>
</div>
/* 所有信息框的基础样式 */
.info-box {
border: 1px solid #ccc;
margin: 20px;
padding: 15px;
background-color: #f9f9f9;
border-radius: 5px;
}
/* 错误信息框的特定样式 */
.error {
border-left: 5px solid red;
background-color: #ffebeb;
}
/* 成功信息框的特定样式 */
.success {
border-left: 5px solid green;
background-color: #e6ffed;
}

在这个例子中:

  • 所有 class="info-box" 的 <div> 元素都会获得基础样式。
  • 第二个 <div> 有两个类 (info-box 和 error)。它会获得基础样式加上特定的错误样式。
  • 第三个 <div> 有 info-box 和 success 类,会获得基础样式和成功样式。
  • 多个类名在 class 属性中用空格分隔。

的 class 属性同样适用于内联元素(inline element),例如 <span>、<a>、** 等,允许你为文本的特定部分设置样式。

示例:高亮显示段落中的文本。

<h1>Product Announcement</h1>
<p>Please read the <span class="highlight-important">critical update notes</span> before proceeding.</p>
<p>Standard terms and conditions apply.</p>
.highlight-important {
background-color: yellow;
color: #333;
font-weight: bold;
}
  • class:可用于多个元素。一个元素可以有多个类(用空格分隔)。主要用于 CSS 样式设置和通过 JavaScript 对元素进行分组。
  • id:在整个 HTML 文档中必须是唯一的。一个元素只能有一个 ID。用于唯一标识一个元素,常用于 JavaScript 操作或通过片段标识符(fragment identifier)(#element-id)进行链接。

最佳实践:使用类用于可复用的样式和分组。在必要时使用 ID 用于唯一标识符。