You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

纯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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 02:36:07