class 与 id
class 复用样式、id 唯一标识、CSS 选择器优先级
class 与 id
class 和 id 是 HTML 最重要的两个属性——用来标识元素,配合 CSS 样式和 JavaScript。
学完本章你将: 掌握 class 复用样式、id 唯一标识、CSS 选择器。
class(可复用)
html
<style>
.highlight { background-color: yellow; }
.text-red { color: red; }
.big { font-size: 20px; }
</style>
<p class="highlight">高亮段落</p>
<p class="highlight text-red big">同时应用多个类</p>
<p class="highlight">又一个高亮</p>
💡 一个元素可以有多个 class,用空格分隔。
id(唯一标识)
html
<style>
#main-title { color: blue; font-size: 28px; }
</style>
<h1 id="main-title">页面主标题</h1>
<!-- ❌ 同一页面中 id 不能重复 -->
<!-- <h2 id="main-title">不能再用了</h2> -->
选择器优先级
html
<!-- id 优先级 > class 优先级 > 标签名 -->
<style>
p { color: black; } /* 标签选择器——低 */
.text { color: green; } /* class 选择器——中 */
#special { color: red; } /* id 选择器——高 */
</style>
<p class="text" id="special">这是什么颜色?</p>
<!-- 红色——id 优先级最高 -->
JS 操作
html
<button id="btn" class="primary">点击</button>
<script>
// 通过 id 获取(一个)
document.getElementById("btn")
// 通过 class 获取(多个)
document.getElementsByClassName("primary")
</script>