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

如何使用Flex布局实现五盒子四角加中心的特殊分布?

实现四个角落+中心的盒子布局

下面提供两种简洁的实现方案,满足你将5个盒子分别放在容器四个角落和中心的需求:

方案一:绝对定位实现(兼容旧浏览器)

通过给容器设置相对定位,再给每个盒子设置绝对定位来精准控制位置:

.container {
  width: 240px;
  height: 200px;
  border: 1px solid gray;
  position: relative; /* 作为内部绝对定位元素的参考容器 */
}

.container > div {
  width: 80px;
  height: 50px;
  border: 1px solid red;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 四个角落定位 */
#one {
  position: absolute;
  top: 0;
  left: 0;
}

#two {
  position: absolute;
  top: 0;
  right: 0;
}

#three {
  position: absolute;
  bottom: 0;
  left: 0;
}

#four {
  position: absolute;
  bottom: 0;
  right: 0;
}

/* 中心盒子:基于容器居中 */
#five {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /* 让盒子自身中心与容器中心重合 */
}

HTML结构保持你原来的代码即可,无需修改。

方案二:CSS Grid实现(现代简洁方案)

利用Grid的网格划分能力,直接将容器拆分为3×3的网格,把盒子放到对应位置:

.container {
  width: 240px;
  height: 200px;
  border: 1px solid gray;
  display: grid;
  /* 定义3列3行:左右列/上下行匹配盒子尺寸,中间列/行占据剩余空间 */
  grid-template-columns: 80px 1fr 80px;
  grid-template-rows: 50px 1fr 50px;
}

.container > div {
  border: 1px solid red;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 定位各个盒子到对应网格区域 */
#one { grid-area: 1 / 1; } /* 第1行第1列 */
#two { grid-area: 1 / 3; } /* 第1行第3列 */
#three { grid-area: 3 / 1; } /* 第3行第1列 */
#four { grid-area: 3 / 3; } /* 第3行第3列 */
#five { 
  grid-area: 2 / 2; /* 第2行第2列 */
  place-self: center; /* 确保盒子在单元格内居中 */
}

HTML结构同样无需修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 06:03:19