如何用CSS3实现两个水平全屏div,第二个自动占剩余屏幕高度
纯CSS实现顶部固定高度、底部自动填充剩余高度的布局
嘿,这个需求用纯CSS完全可以搞定,再也不用依赖JS啦!我猜你应该是想让两个div垂直堆叠(毕竟水平排列且宽度100%的话会自动换行,不符合你说的“第一个div之外的剩余屏幕高度”的需求),下面就给你分享几个最实用的方案:
方案1:Flexbox(最推荐,现代浏览器首选)
Flexbox是目前布局的首选方案,代码简洁且兼容性好(支持IE11+及所有现代浏览器)。核心思路是给父容器设置垂直方向的弹性布局,让底部div自动“伸展”占满剩余空间:
<!DOCTYPE html> <html> <head> <style> /* 先确保根元素占满整个视口高度 */ html, body { margin: 0; padding: 0; height: 100%; } /* 父容器设置弹性布局,方向垂直 */ .container { display: flex; flex-direction: column; height: 100%; } /* 顶部div:固定高度,禁止被压缩 */ .top-div { height: 120px; flex-shrink: 0; /* 关键:防止内容过多时顶部div被挤压 */ background-color: #f5f5f5; padding: 10px; } /* 底部div:自动填充剩余空间 */ .bottom-div { flex: 1; /* 等价于 flex-grow: 1; flex-shrink: 1; flex-basis: 0; */ background-color: #e8e8e8; padding: 10px; overflow: auto; /* 如果底部内容超出高度,自动显示滚动条 */ } </style> </head> <body> <div class="container"> <div class="top-div">我是固定高度120px的顶部区域</div> <div class="bottom-div">我是自动填充剩余高度的底部区域<br>内容再多也不怕,超出会自动滚动哦😉</div> </div> </body> </html>
方案2:CSS Grid(更直观,代码更短)
Grid布局也是现代浏览器的宠儿,它的布局逻辑更直观,一行代码就能搞定行高分配:
<!DOCTYPE html> <html> <head> <style> html, body { margin: 0; padding: 0; height: 100%; } /* 父容器设置网格布局,指定第一行120px,第二行占剩余 */ .container { display: grid; grid-template-rows: 120px 1fr; /* 核心:1fr表示“剩余空间的1份” */ height: 100%; } .top-div { background-color: #f5f5f5; padding: 10px; } .bottom-div { background-color: #e8e8e8; padding: 10px; overflow: auto; } </style> </head> <body> <div class="container"> <div class="top-div">固定高度120px的顶部</div> <div class="bottom-div">自动填充剩余高度的底部</div> </div> </body> </html>
方案3:绝对定位+Calc(兼容老浏览器)
如果需要兼容IE10及更早的浏览器,可以用绝对定位的方式,不过这种方案需要注意父容器的定位设置:
<!DOCTYPE html> <html> <head> <style> html, body { margin: 0; padding: 0; height: 100%; position: relative; /* 父容器设置相对定位,作为绝对定位的参考 */ } .top-div { height: 120px; background-color: #f5f5f5; padding: 10px; } .bottom-div { position: absolute; top: 120px; /* 顶部对齐顶部div的底部 */ left: 0; right: 0; bottom: 0; /* 底部对齐父容器底部 */ background-color: #e8e8e8; padding: 10px; overflow: auto; } </style> </head> <body> <div class="top-div">固定高度120px的顶部</div> <div class="bottom-div">自动填充剩余高度的底部</div> </body> </html>
小提示
- 如果你的布局不是直接基于
body,而是嵌套在其他容器里,记得给所有父容器都设置height: 100%,确保高度能传递下去。 - 给底部div加上
overflow: auto可以避免内容溢出时撑破布局,自动显示滚动条更友好。
内容的提问来源于stack exchange,提问作者Mohammad Hani
相关产品推荐
相关产品推荐

