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

制作3x3 Div网格遇问题:列内仅两个Div呈inline,第三个换行

解决3x3网格列内元素换行问题

问题原因

  • 重复ID错误:HTML中<div id="two">和<div id="three">重复使用,ID在文档中必须唯一,应替换为class。
  • inline-block空白占位:inline-block元素之间的换行/空格会被解析为空白字符,占用额外宽度,三个33.333%宽度的元素加空白总宽度超过父容器100%,导致第三个元素换行。

解决方案(推荐用Flex布局,更简洁可靠)

Flex布局天生适合这种等分排列的场景,无需处理空白问题,代码更简洁:

修改后的CSS

.one {
  height: 30vh;
  width: 30vh;
}

.two {
  width: 100%;
  height: 33.333%;
  display: flex; /* 启用flex布局 */
}

.three {
  flex: 1; /* 让每个元素平分父容器宽度 */
  height: 100%;
  /* 加边框方便查看效果,可按需删除 */
  border: 1px solid #ccc;
  box-sizing: border-box; /* 边框计入宽度,避免超出容器 */
}

修改后的HTML

<div class="one">
  <div class="two">
    <div class="three"></div>
    <div class="three"></div>
    <div class="three"></div>
  </div>
  <div class="two">
    <div class="three"></div>
    <div class="three"></div>
    <div class="three"></div>
  </div>
  <div class="two">
    <div class="three"></div>
    <div class="three"></div>
    <div class="three"></div>
  </div>
</div>

若坚持使用inline-block的修复方法

如果一定要用inline-block,需要处理空白问题,同时修正ID:

  1. 把HTML中所有ID改为class
  2. 给父元素.two设置font-size: 0;,消除元素间空白,再给.three恢复字体大小
  3. 给.three加上box-sizing: border-box;,避免边框/内边距导致宽度超出

示例CSS:

.one {
  height: 30vh;
  width: 30vh;
}

.two {
  width: 100%;
  height: 33.333%;
  font-size: 0; /* 消除inline-block元素间的空白 */
}

.three {
  height: 100%;
  width: 33.333%;
  display: inline-block;
  font-size: 16px; /* 恢复默认字体大小 */
  border: 1px solid #ccc;
  box-sizing: border-box;
}

内容的提问来源于stack exchange,提问作者Iver Hallset

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 05:33:10