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

如何实现Container固定居中且Inner div在Outer div中心重叠布局?

布局解决方案

实现目标

  • inner 与 outer div 堆叠显示,inner 位于 outer 中心位置
  • container 容器以固定定位方式在网页水平、垂直方向居中

修改后的代码

CSS 代码

.container{
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.outer{
  position: relative;
  width: 200px;
  aspect-ratio: 1;
  border: 5px solid gold;
}
.inner{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100px;
  aspect-ratio: 1;
  border: 5px solid gold;
}

HTML 代码

<div class="container">
  <div class="outer">
    <div class="inner"></div>
  </div>
</div>

关键调整说明

  • container 居中:通过 position: fixed 配合 top: 50%、left: 50% 和 transform: translate(-50%, -50%),让固定定位的容器精准居中,不受自身尺寸影响。
  • inner 相对于 outer 居中:将 outer 的定位改为 relative,使其成为 inner 的定位参考父级;给 inner 设置偏移和位移属性,实现基于 outer 的居中堆叠效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 00:32:40