无需JavaScript实现滚动时收缩带图文的粘性头部
无JavaScript实现滚动裁剪式Sticky Header
需求说明
- 初始状态:头部以图片为背景,包含标题和描述文本,占据页面50%高度
- 滚动状态:头部高度缩小至10%,背景图自动裁剪,仅保留标题并固定在顶部
优化后的无JS实现方案
不需要重复创建两个头部容器,利用CSS position: sticky 和伪类即可实现需求,结构更简洁且语义化:
HTML代码
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Sticky Header Demo</title> </head> <body> <header class="sticky-header"> <div class="header-content"> <h1 class="header-title">Title</h1> <div class="header-description"> <h2>Description:</h2> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p> </div> </div> </header> <main> <section> <h2>The problem:</h2> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p> </section> <section> <h2>The problem:</h2> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p> </section> <section> <h2>更多内容</h2> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam, voluptatum.</p> </section> <section> <h2>更多内容</h2> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam, voluptatum.</p> </section> <section> <h2>更多内容</h2> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam, voluptatum.</p> </section> </main> </body> </html>
CSS代码
html, body { margin: 0; padding: 0; } .sticky-header { background: yellow url('../image/titel_image.jpeg') center/cover no-repeat; text-align: center; width: 100%; height: 50vh; /* 初始占视口一半高度 */ position: sticky; top: 0; display: flex; align-items: center; justify-content: center; transition: height 0.3s ease; /* 平滑过渡高度变化 */ } /* 检测header是否处于固定状态,触发样式变化 */ .sticky-header:is(:sticky) { height: 10vh; /* 固定后缩小高度 */ } .header-content { background-color: white; padding: 1rem 2rem; transition: padding 0.3s ease; } /* 固定后隐藏描述文本 */ .sticky-header:is(:sticky) .header-description { display: none; } /* 固定后调整标题容器内边距,适配小高度 */ .sticky-header:is(:sticky) .header-content { padding: 0.5rem 2rem; } main { padding: 2rem; } section { margin-bottom: 3rem; }
核心原理说明
position: sticky固定逻辑:头部初始在文档流中占据50vh高度,当页面滚动至头部触达视口顶部时,自动切换为固定定位:sticky伪类触发样式:利用该伪类检测头部的固定状态,动态修改高度并隐藏描述文本- 背景图自动裁剪:通过
background-size: cover确保背景图始终填充容器,高度缩小时自动裁剪边缘区域,保留中心内容 - 平滑过渡:添加
transition属性让高度和内边距变化更自然
原代码存在的问题
- 重复创建标题DOM,增加维护成本
- 使用
absolute定位导致布局依赖硬编码的margin-top值,适配性差 z-index层级设置不合理,易出现元素遮挡问题
内容的提问来源于stack exchange,提问作者confusedstudent
相关产品推荐
相关产品推荐

