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

如何实现不等宽2x2 Flex网格并支持移动端响应式堆叠

问题根源

你的布局显示异常是几个基础配置遗漏导致的:

  • 最外层.container未开启flex布局,子元素(侧边栏、右侧内容区)默认按块级规则纵向排列,给子元素设置flex相关宽度属性自然不会生效;你预先定义的.flex-row类没有挂载到任何DOM节点上,完全没有发挥作用
  • 包裹4个内容块的右侧容器被设置了flex-direction: column,内部元素默认纵向排布,无法形成2x2的网格结构
  • 没有编写响应式媒体查询规则,无法根据视口宽度自动切换布局模式
  • 没有做盒模型重置,padding、margin计算容易撑破容器导致换行错乱

修正后完整代码

CSS部分

/* 盒模型重置,避免宽度计算异常 */
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

/* 最外层容器开启flex,是内部元素flex属性生效的前提 */
.container {
  display: flex;
  width: 100%;
  min-height: 100vh;
}

/* 桌面端侧边栏固定宽度 */
.sidebar-menu-col {
  flex: 0 0 15em;
  background: #333;
  color: #fff;
  padding: 1rem;
  margin: 6px;
}

/* 右侧内容区容器:桌面端横向排列+自动换行 */
.content-wrap {
  flex: 1;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

/* 内容块通用样式 */
.flex-col {
  margin: 6px;
  padding: 2rem 0;
  background-color: black;
  display: flex;
  justify-content: center;
  align-items: center;
  /* 宽度减去左右margin总和,刚好一行容纳2个块 */
  flex: 0 0 calc(50% - 12px);
  color: white;
}

/* 移动端响应式断点,可根据需求调整阈值 */
@media screen and (max-width: 768px) {
  .container {
    flex-direction: column;
  }
  /* 侧边栏移动端占满宽度,如果要做汉堡按钮可默认设置display: none */
  .sidebar-menu-col {
    flex: 0 0 auto;
    width: calc(100% - 12px);
  }
  .content-wrap {
    flex-direction: column;
  }
  .flex-col {
    flex: 1 1 auto;
    width: calc(100% - 12px);
  }
}

HTML部分

<div class="container">
  <div class="sidebar-menu-col">
    menu here
  </div>
  <div class="content-wrap">
    <div class="flex-col">A1</div>
    <div class="flex-col">B1</div>
    <div class="flex-col">A2</div>
    <div class="flex-col">B2</div>
  </div>
</div>

关键逻辑说明
  • 侧边栏设置flex: 0 0 15em即可固定宽度不被压缩,右侧.content-wrap设置flex: 1会自动占满侧边栏以外的剩余宽度
  • 桌面端右侧内容区开启换行后,子元素设置50%基础宽度(扣除margin),自然形成2x2网格
  • 内容块的DOM顺序和你要求的移动端堆叠顺序完全一致,不需要额外调整order属性,纵向排列时自动匹配A1→B1→A2→B2的顺序
  • 如果要实现移动端汉堡菜单效果,只需要默认给.sidebar-menu-col加display: none,写少量JS控制汉堡按钮点击时切换侧边栏的显示状态即可,不会影响内容区的堆叠逻辑

内容的提问来源于stack exchange,提问作者I. Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 21:45:44