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

如何让经过transform的元素置于另一个元素后方?

如何让经过transform的background div保持在foreground后方?

首先来看你提供的原始代码:

CSS代码

.container { width: 100px; height: 100px; font-size: 100px; } 
.background { color: red; width: 100%; height: 100%; margin-bottom: -100%; transform: rotate(90deg); } 
.foreground { color: blue; width: 100%; height: 100%; }

HTML代码

<div class="container"> 
  <div class="background">B</div> 
  <div class="foreground">F</div> 
</div>

这个问题的核心原因是:当元素应用了transform属性后,会自动创建一个新的堆叠上下文(stacking context)。默认情况下,没有transform的元素不会触发堆叠上下文,所以经过transform处理的.background元素堆叠层级会比.foreground更高,导致它跑到了前面。

要解决这个问题,我们只需要让.foreground也创建堆叠上下文,同时通过z-index明确指定它的层级更高即可,具体修改如下:

修改后的CSS代码

.container { 
  width: 100px; 
  height: 100px; 
  font-size: 100px;
  position: relative; /* 让容器成为堆叠上下文,确保子元素的z-index在容器内部生效 */
} 
.background { 
  color: red; 
  width: 100%; 
  height: 100%; 
  margin-bottom: -100%; 
  transform: rotate(90deg);
  z-index: 1; /* 设置较低的层级 */
} 
.foreground { 
  color: blue; 
  width: 100%; 
  height: 100%;
  transform: translate(0); /* 用不改变位置的transform触发堆叠上下文 */
  z-index: 2; /* 设置比background更高的层级 */
}

这样修改后,.foreground会因为transform: translate(0)创建自己的堆叠上下文,同时z-index:2确保它在.background(z-index:1)的上方,就能实现你想要的效果了。

另外还有一种简化思路:如果你的容器没有设置position: relative,可以直接给.background设置z-index: -1,不过这种方式要注意.background可能会跑到容器的后方,所以更稳妥的还是上面的方法,让两个元素都处于容器的堆叠上下文内,明确控制层级。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:44:35