粘性表头
本课属于 Coddy Tailwind CSS 学习旅程的“响应式 UI 模式”单元。第 24 课,共 55 课。
保持列标签可见,可以让长表格更易于浏览。使用一个有边界的滚动容器,然后为表头单元格应用 sticky 和顶部偏移。粘性定位会让这些单元格保持在文档流中,直到滚动边界到达该偏移位置。
<div class="h-48 overflow-y-auto"><table><thead><tr><th scope="col" class="sticky top-6 z-10 bg-white">Session</th></tr></thead><tbody><tr><td>Workshop</td></tr></tbody></table></div>这个示例使用 24px 的内边距,因为标题上方的另一控件占用了这部分空间。top-0 表示不预留空间;top-8 预留 32px。相关边界是最近的可滚动祖先元素,不一定是页面视口。
为粘性表头设置不透明背景和合适的堆叠层级,例如 z-10。透明的表头可能会让正文透出来。保留原生表头单元格和作用域,这样在视觉上固定表头的同时,也能保留数据关系。
挑战
中等让列标题固定在提供的 160px 可滚动表格区域顶部。两个表头单元格都必须使用粘性定位,顶部偏移量为 0,背景为不透明的白色,堆叠层级为 10。保留标题和表头作用域。
保留提供的内容、语义元素和 ID。编辑指定的工具类。编辑后按“运行”预览,然后按“检查”/运行代码来评分。提供的 JavaScript 只读。
亲手试试
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Interface workshop</title><link rel="stylesheet" href="./styles.css"></head><body>
<div id="wrap" class="h-40 overflow-y-auto"><table id="table" class="w-full border-separate border-spacing-0"><caption>Studio schedule</caption><thead><tr><th scope="col" class="static bg-white">Session</th><th scope="col" class="static bg-white">Room</th></tr></thead><tbody><tr id="r1" class=""><th scope="row">Session 1</th><td id="cell1">Room 1</td></tr><tr id="r2" class=""><th scope="row">Session 2</th><td id="cell2">Room 2</td></tr><tr id="r3" class=""><th scope="row">Session 3</th><td id="cell3">Room 3</td></tr><tr id="r4" class=""><th scope="row">Session 4</th><td id="cell4">Room 4</td></tr><tr id="r5" class=""><th scope="row">Session 5</th><td id="cell5">Room 5</td></tr><tr id="r6" class=""><th scope="row">Session 6</th><td id="cell6">Room 6</td></tr><tr id="r7" class=""><th scope="row">Session 7</th><td id="cell7">Room 7</td></tr><tr id="r8" class=""><th scope="row">Session 8</th><td id="cell8">Room 8</td></tr><tr id="r9" class=""><th scope="row">Session 9</th><td id="cell9">Room 9</td></tr><tr id="r10" class=""><th scope="row">Session 10</th><td id="cell10">Room 10</td></tr><tr id="r11" class=""><th scope="row">Session 11</th><td id="cell11">Room 11</td></tr><tr id="r12" class=""><th scope="row">Session 12</th><td id="cell12">Room 12</td></tr></tbody></table></div>
</body></html>
这节课包含一个小测验。开始学习即可作答,并记录你的进度。