如何将固定横幅高度设为屏幕50%且滚动时完全可见?
解决方案
要实现底部固定横幅高度限制为屏幕50%且滚动时完全可见,需要从两个核心维度调整:固定横幅的定位与高度控制,以及主内容的底部留白避免遮挡。
关键调整点
- 横幅改用
position: fixed固定在底部,搭配max-height: 50vh限制最大高度,同时添加overflow-y: auto,确保内容超过50vh时内部滚动,不会超出屏幕范围。 - 为主内容容器添加
padding-bottom: 50vh,让最后部分内容不会被固定的横幅遮挡。
修改后的完整代码
CSS 部分
* { margin: 0; padding: 0; box-sizing: border-box; } .wrapper { position: relative; width: 100%; background: green; /* 添加底部内边距,避免内容被横幅遮挡 */ padding-bottom: 50vh; } .wrapper > p { padding: 2rem; } .banner { position: fixed; /* 固定在底部 */ bottom: 0; left: 0; right: 0; max-height: 50vh; /* 限制最大高度为屏幕一半 */ overflow-y: auto; /* 内容超出时内部滚动 */ background: blue; color: #fff; z-index: 10; width: 100%; } .banner-title { color: #fff; font-family: "Bebas Neue Bold", sans-serif; font-size: 2.7rem; line-height: 1.25926; letter-spacing: 0.1rem; margin-bottom: 5px; } .banner-container { background-color: blue; position: relative; } .banner-inner { width: calc(100% - 8.33333%); margin-left: 4.16667%; margin-bottom: 3rem; margin-top: 3rem; } .banner-privacy { position: relative; padding: 0; } .banner-privacy > p { color: #fff; font-size: 1.4rem; line-height: 1.71429; margin-bottom: 30px; max-height: 6rem; overflow: auto; font-family: "PT Sans", sans-serif; color: grey; float: none; position: relative; } .banner-btn-wrapper { display: flex; flex-direction: column; margin-bottom: -1em; } .banner-btn { flex: 0 0 100%; margin-bottom: 1em; background-color: grey; border: 2px solid #fff; color: #fff; display: flex; font-family: "PT Sans Bold", sans-serif; font-size: 1.6rem; min-width: min-content; overflow: hidden; padding: 0.8em 1.9em; text-align: center; }
HTML 部分(结构保留原逻辑)
<main class="wrapper"> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>Hello</p> <p>last Hello</p> <div class="banner"> <div class="banner-container"> <div class="banner-inner"> <div class="banner-title"> Cookie Banner </div> <div class="banner-privacy"> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Sed fugit amet porro labore iure adipisci quasi reprehenderit, tempora voluptas placeat cumque, eligendi dolorum laborum reiciendis, deleniti eaque! Mollitia, eius cupiditate?</p> </div> <div class="banner-btn-wrapper"> <button class="banner-btn">Lorem ipsum dolor sit amet consectetur</button> <button class="banner-btn">Lorem ipsum dolor sit amet consectetur</button> <button class="banner-btn">Lorem ipsum dolor sit amet consectetur</button> </div> </div> </div> </div> </main>
效果说明
- 横幅始终固定在屏幕底部,最大高度为屏幕的50%;若横幅内容超出该高度,内部会生成垂直滚动条,整个横幅不会超出屏幕边界。
- 主内容的底部留白确保最后一段内容能完全显示,不会被固定横幅遮挡。
内容的提问来源于stack exchange,提问作者FD3
相关产品推荐
相关产品推荐

