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

如何仅用Flexbox实现指定布局(禁用float与Bootstrap)

用Flexbox实现目标布局的正确写法

先纠正你原代码里的几个错误

  • flex-shrink 只能设置数字(代表收缩比例),写30px这种长度值是无效的
  • align-items 是Flex容器的专属属性,写在子元素.one里不会生效
  • .four使用了float,不符合要求,必须改用Flex布局实现

实现目标布局的完整代码

<style>
/* 外层容器,垂直排列所有子元素 */
.container {
  display: flex;
  flex-direction: column;
  gap: 5px; /* 元素之间的间距 */
  padding: 5px;
}

/* 顶部通宽区块 */
.three {
  background-color: blue;
  height: 100px; /* 高度可按需调整 */
}

/* 放置左右区块的水平容器 */
.row-container {
  display: flex;
  gap: 5px;
}

/* 左侧宽区块:设置基础宽度,扩展比例为3,允许收缩 */
.one {
  background-color: blue;
  flex: 3 1 300px;
  height: 200px; /* 高度可按需调整 */
}

/* 右侧窄区块:扩展比例为1,和左侧保持3:1的宽度比例 */
.two {
  background-color: blue;
  flex: 1 1 100px;
  height: 200px; /* 高度可按需调整 */
}

/* 底部通宽区块 */
.four {
  background-color: blue;
  height: 80px; /* 高度可按需调整 */
}
</style>
<body>
  <div class="container">
    <div class="three"></div>
    <div class="row-container">
      <div class="one"></div>
      <div class="two"></div>
    </div>
    <div class="four"></div>
  </div>
</body>

核心布局逻辑

  1. 外层.container通过flex-direction: column,让顶部区块、左右区块容器、底部区块垂直顺序排列
  2. 左右两个区块放在.row-container中,利用Flex默认的水平排列特性实现并排
  3. 用flex简写属性控制区块的宽度比例:.one的flex:3 1 300px表示它会占据剩余空间的3份,.two的flex:1 1 100px表示占据1份,同时两者在空间不足时会自动收缩,保证布局适配不同屏幕
  4. 全程未使用float和任何框架,完全依靠Flexbox实现需求

内容的提问来源于stack exchange,提问作者Hania Hafeez Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 17:09:55