实战骨架:吸顶头部、侧栏与粘底页脚
把 Flex、Grid、sticky 组合成一个可直接复用的页面骨架,附移动端处理与常见塌陷排查。
前面几篇分别讲了 Flex、Grid、定位和尺寸。这一篇把它们拼成一个真实页面骨架:吸顶头部、可滚动主区、粘性侧栏、贴底页脚。这个结构能覆盖博客、文档、后台的大部分场景。
整体网格#
.page {
display: grid;
grid-template-columns: 232px minmax(0, 1fr);
grid-template-rows: auto 1fr auto;
grid-template-areas:
"head head"
"side main"
"foot foot";
min-height: 100dvh; /* 至少一屏,页脚才能贴底 */
}
.page > .head { grid-area: head; }
.page > .side { grid-area: side; }
.page > .main { grid-area: main; min-width: 0; }
.page > .foot { grid-area: foot; }1fr 在行方向上让主区吃掉剩余高度,页脚自然被推到底部。不需要任何 height: 100% 或 JS 计算。
吸顶头部#
.head {
position: sticky;
top: 0;
z-index: 40;
background: rgb(255 255 255 / .88);
backdrop-filter: saturate(180%) blur(14px);
border-bottom: 1px solid #e5e9f0;
}半透明 + 模糊是现在的标准做法,但要注意两点:必须有背景色(纯 blur 在部分浏览器下会导致文字与背景糊在一起),必须设 z-index,否则会被正文里的元素盖住。
粘性侧栏#
.side {
position: sticky;
top: 88px; /* 头部高度 + 间距 */
align-self: start; /* 不拉伸,才有滚动距离 */
max-height: calc(100dvh - 104px);
overflow-y: auto;
padding: 24px 0;
}移动端:侧栏变成横向滚动条#
@media (max-width: 900px) {
.page {
grid-template-columns: 1fr;
grid-template-areas: "head" "side" "main" "foot";
}
.side {
position: static;
max-height: none;
display: flex;
gap: 8px;
overflow-x: auto;
border-bottom: 1px solid #e5e9f0;
padding: 12px 16px;
-webkit-overflow-scrolling: touch;
}
.side a { white-space: nowrap; flex: 0 0 auto; }
}横向滚动比汉堡菜单更好:不用点开、不遮挡内容、也不需要 JS。副作用是需要隐藏滚动条才好看,用 scrollbar-width: none 加 ::-webkit-scrollbar { display: none }。
排查「页面塌了」的四步#
- 看有没有横向滚动条:给所有元素加
outline: 1px solid red,超出的那个一眼可见。 - 查固定宽度:
width: 1200px、min-width: 600px、white-space: nowrap是三大元凶。 - 查图片:没写
max-width: 100%的图片会按原始尺寸撑开。 - 查长文本:连续无空格的英文、URL、代码块,需要
overflow-wrap: anywhere。
/* 万能兜底,但别当第一选择 */
.main { overflow-wrap: anywhere; }
img, video, svg { max-width: 100%; height: auto; }这套骨架的取舍#
它没有用任何框架,因为页面骨架本来就不需要框架。代价是响应式要自己写——但也只有一处媒体查询。真正复杂的从来不是骨架,而是骨架里的组件。
接下来进入现代 CSS::has()、原生嵌套、视图过渡,这些是 2024 年之后真正能上生产的新能力。