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

如何实现div元素重叠?当前效果与预期不符,寻求解决方案

问题描述

我想要实现的效果是:深灰色小方块(square1)叠加在浅灰色的.base方块上方,且处于合适的位置;但目前深灰色小方块出现在了.base方块的左下方,没能实现预期的叠加布局。

以下是我的代码:

CSS 代码

.base {
  background: #e2e2e2;
  width: 1020px;
  height: 350px;
  position: absolute;
  top: 100px;
  left: 130px;
}

HTML 代码

<div class="section5" style="width:100%;background-color:#f5f5f5;height:550px;position: relative;">
  <div class="base"></div>
  <div class="square1" style="width:255px;height:193px;background-color:#969696; z-index:1;"></div>
</div>
解决方案

问题出在.square1未设置定位属性——z-index仅对**定位元素(position值为relative、absolute、fixed或sticky)**生效,同时无定位的元素会按照文档流排布,无法叠加在绝对定位的.base上方。

修改方式如下:

调整后的代码(内联样式版)

<div class="section5" style="width:100%;background-color:#f5f5f5;height:550px;position: relative;">
  <div class="base"></div>
  <div class="square1" style="width:255px;height:193px;background-color:#969696; position: absolute; top: 150px; left: 180px; z-index:1;"></div>
</div>

规范版(样式分离)

CSS 代码

.base {
  background: #e2e2e2;
  width: 1020px;
  height: 350px;
  position: absolute;
  top: 100px;
  left: 130px;
}

.square1 {
  width:255px;
  height:193px;
  background-color:#969696;
  position: absolute;
  /* 可根据需求调整top/left值,控制方块在.base上的位置 */
  top: 150px;
  left: 180px;
  z-index:1;
}

HTML 代码

<div class="section5" style="width:100%;background-color:#f5f5f5;height:550px;position: relative;">
  <div class="base"></div>
  <div class="square1"></div>
</div>

核心要点:

  • 给.square1添加position: absolute(或relative),让z-index生效,同时使其相对于父元素.section5(已设置relative定位)进行定位
  • 通过top和left属性调整.square1的位置,使其落在.base的上方区域

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 06:03:13