标签页
本课属于 Coddy HTML 学习旅程的“前端实践”单元。第 21 课,共 35 课。
标签页可以将内容整理到不同的单元中,同时让所有内容都保留在同一个页面上。用户无需滚动浏览很长的页面,只需点击标签页,就能在不同的内容面板之间切换。你经常会在设置页面、仪表板或产品说明中看到标签页(例如,详情、评价、常见问题)。
我们可以使用以下内容创建选项卡,而不需要 JavaScript:
- 单选按钮(这样一次只能激活一个选项卡)
- 充当可点击选项卡按钮的标签
- 使用 CSS 选择器(
:checked)显示对应的内容
HTML:
<div class="tabs">
<input type="radio" id="tab1" name="tab" checked>
<label for="tab1">Tab 1</label>
<div id="content1" class="tab-content">This is the content of Tab 1.</div>
<input type="radio" id="tab2" name="tab">
<label for="tab2">Tab 2</label>
<div id="content2" class="tab-content">This is the content of Tab 2.</div>
<input type="radio" id="tab3" name="tab">
<label for="tab3">Tab 3</label>
<div id="content3" class="tab-content">This is the content of Tab 3.</div>
</div>CSS:
<style>
/* 隐藏单选按钮 */
input { display: none; }
/* 选项卡标签 */
label {
padding: 5px 10px;
background: lightgray;
cursor: pointer;
}
/* 默认隐藏内容 */
.tab-content { display: none; padding: 10px; border: 1px solid #ccc; }
/* 选中单选按钮时显示内容 */
#tab1:checked ~ #content1,
#tab2:checked ~ #content2 {
display: block;
}
/* 突出显示当前选项卡 */
#tab1:checked + label,
#tab2:checked + label {
background: steelblue;
color: white;
}
</style>这里有一条可以快速提醒学生的话:
+(相邻兄弟)→ 选择紧接着的元素。~(通用兄弟)→ 选择后面的任意兄弟元素(不只是下一个)。
挑战
简单给定的初始 HTML 已经设置好两个标签页。你的任务是扩展并改进这个标签页系统。
- 再添加一个标签页 “Sleep”:
- 标签:
Sleep - 内容:“Good sleep helps recovery and focus. Aim for 7 to 9 hours per night and keep a regular schedule.”
- 标签:
- 将
#tab3:checked ~ #content3添加到选中时显示标签页内容的 CSS 选择器中。
亲手试试
<!DOCTYPE html>
<html>
<head>
<title>Tabs</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
background: #f9f9f9;
}
.tabs {
display: flex;
flex-direction: column;
width: 350px;
}
/* Hide the radio inputs */
.tabs input {
display: none;
}
/* Tab labels */
.tabs label {
padding: 10px;
background: #eee;
cursor: pointer;
border: 1px solid #ccc;
}
.tabs label:hover {
background: #ddd;
}
/* Tab content */
.tab-content {
display: none;
border: 1px solid #ccc;
padding: 10px;
background: #fff;
line-height: 1.5;
}
/* Show content when radio is checked */
#tab1:checked ~ #content1,
#tab2:checked ~ #content2 {
display: block;
}
/* Highlight active tab */
#tab1:checked + label,
#tab2:checked + label,
#tab3:checked + label {
background: #4cafef;
color: white;
}
</style>
</head>
<body>
<div class="tabs">
<input type="radio" id="tab1" name="tab" checked>
<label for="tab1">Nutrition</label>
<div id="content1" class="tab-content">
<h3>Nutrition</h3>
<p>A balanced diet fuels your body and mind. Focus on fruits, vegetables, whole grains, and lean proteins. Avoid too much processed food.</p>
</div>
<input type="radio" id="tab2" name="tab">
<label for="tab2">Exercise</label>
<div id="content2" class="tab-content">
<h3>Exercise</h3>
<p>Daily movement strengthens your body and reduces health risks. Even a 30-minute walk or stretching makes a difference.</p>
</div>
</div>
</body>
</html>这节课包含一个小测验。开始学习即可作答,并记录你的进度。
前端实践中的所有课
自己练习: Web 在线编辑器