纯CSS可调整大小的网格布局实现需求
解决方案
需求回顾
- 实现指定结构的三元素网格布局:
------------ |one | two | ------------ | three | ------------ - 支持拖动调整
one与two的横向宽度、three与上方元素的纵向高度,且三个元素始终填满容器100%宽高,全程无间隙 - 元素内容溢出时需自动处理,避免超出布局范围
实现代码
HTML
<!DOCTYPE html> <html> <body> <div class="container"> <div class="one">可拖动调整宽度 - 内容超出时自动出现滚动条</div> <div class="two">可拖动调整宽度 - 内容超出时自动出现滚动条</div> <div class="three">可拖动调整高度 - 内容超出时自动出现滚动条</div> </div> </body> </html>
CSS
* { margin: 0; padding: 0; box-sizing: border-box; } body { overflow: hidden; } .container { display: grid; grid-template-areas: "one two" "three three"; grid-template-rows: auto auto; grid-template-columns: auto auto; width: 100vw; height: 100vh; } .one { grid-area: one; border: 3px dotted blue; overflow: auto; resize: horizontal; min-width: 100px; min-height: 100px; } .two { grid-area: two; border: 3px dotted red; overflow: auto; resize: horizontal; min-width: 100px; min-height: 100px; } .three { grid-area: three; border: 3px dotted black; overflow: auto; resize: vertical; min-height: 100px; }
核心优化说明
- 消除布局间隙:通过
box-sizing: border-box确保元素边框纳入自身尺寸计算,同时清除全局默认边距,彻底避免间隙问题 - 铺满视口布局:容器设置
100vw和100vh尺寸,结合grid-template-columns/rows: auto,让网格轨道跟随子元素尺寸动态调整,始终填满整个视口 - 精准拖动控制:针对不同元素设置对应方向的
resize属性,避免无效拖动;同时设置最小尺寸限制,防止元素被拖至不可用状态 - 溢出内容处理:所有子元素启用
overflow: auto,内容超出时自动生成滚动条,保证布局完整性
内容的提问来源于stack exchange,提问作者Luggie
相关产品推荐
相关产品推荐

