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

如何实现第二个Div内容覆盖上方带斜向背景的Div?

问题描述

需要实现第二个div的内容覆盖在上方的div之上,尝试过两种方法但都存在问题:

  • 使用负外边距:会让所有元素上移,无法实现图片与内容的覆盖效果,调整形状位置时还会看到div-2的背景透出来
  • 使用绝对定位:div-2的高度会塌陷,无法随内容尺寸自适应收缩

效果参考:
效果参考图

原代码

CSS

html,
body {
  margin: 0;
}

* {
  box-sizing: border-box;
  border: 1px solid grey;
}

#div-1 {
  height: 18rem;
  background-color: #fad2e1;
}

#div-2 {
  position: relative;
  padding-bottom: 2rem;
  background-color: #e2ece9;
}

#div-2::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  aspect-ratio: 96/23;
  clip-path: polygon(0% 0, 100% 99%, 100% 100%, 0 100%);
  background-color: #cddafd;
}

#div-2::after {
  content: '';
  position: absolute;
  margin-top: 23.8%;
  top: 0;
  left: 0;
  width: 100%;
  aspect-ratio: 96/23;
  background-image: url('https://raw.githubusercontent.com/ChazUK/hosted-assets/main/layout-positioning/semi-circle.svg');
  background-position: top left;
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

#container {
  position: relative;
  z-index: 10;
}

#image {
  display: block;
  margin-inline: auto;
  width: 15rem;
  height: 18rem;
  background-color: #eae4e9;
}

#content {
  width: 100%;
  height: 18rem;
  max-width: 44rem;
  margin-inline: auto;
  background-color: #fff1e6;
}

HTML

<div id="div-1"></div>
<div id="div-2">
  <div id="container">
    <img id="image" src="" alt="" />
    <div id="content"></div>
  </div>
</div>
解决方案

核心思路是给内容容器设置负顶部外边距实现覆盖,同时通过内边距保证父元素高度自适应,调整伪元素位置避免重叠,具体修改如下:

修改后的关键CSS代码:

#div-2 {
  position: relative;
  padding-bottom: 2rem;
  background-color: #e2ece9;
  /* 给伪元素预留顶部空间,避免和内容重叠 */
  padding-top: calc(23 / 96 * 100%);
}

#div-2::before, #div-2::after {
  /* 把伪元素移回容器上方的原始位置 */
  top: -calc(23 / 96 * 100%);
}

#container {
  position: relative;
  z-index: 10;
  /* 让容器向上移动覆盖div-1,数值匹配图片高度 */
  margin-top: -18rem;
  /* 内边距抵消负外边距,防止内容被裁剪 */
  padding-top: 18rem;
}

说明

  1. 覆盖效果实现:通过#container的margin-top: -18rem让内容向上覆盖div-1,同时用padding-top: 18rem保证容器内的内容不会被裁剪,且不影响div-2的高度自适应。
  2. 伪元素位置修正:将伪元素的top值调整为负的自身高度,让它回到div-2上方的原始位置,避免被容器的负外边距带偏。
  3. 层级控制:保留#container的z-index:10,确保内容始终在伪元素和div-1之上,彻底解决背景透出问题。

调整后既能实现内容覆盖效果,又能保证div-2高度随内容自适应,同时避免了之前方法的各种问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 13:38:32