伪元素与普通元素的层级关系问题浅析

121 阅读2分钟

前言:最近在开发过程中,遇到了要在一个 div 左上角加一个球球的需求,如图:

image.png

按部就班地,先写 dom:

<section className='process-section-step'>
  <Title level={4}>Analyzing your product...</Title>
</section>

然后写 css:

.fourth-process-section-step {
  position: relative;
  display: flex;
  width: 400px;
  padding: 36px;
  align-items: center;
  gap: 10px;
  border-radius: 20px;
  border: 4px solid rgba(253, 224, 218, 0.84);
  background: linear-gradient(180deg, rgba(255, 255, 255, 0.35) 0%, rgba(255, 255, 255, 0.70) 100%);
  backdrop-filter: blur(14px);
}

.fourth-process-section-step::before {
  content: '';
  position: absolute;
  top: -30px;
  left: -35px;
  width: 70px;
  height: 70px;
  border-radius: 50%;
  border: 5px solid #FFD813;
  flex-shrink: 0;
  background: radial-gradient(106.67% 106.67% at 50% 15.15%, rgba(255, 242, 0, 0.90) 0%, #FFB006 91.67%);
  opacity: 0.7;
}

本以为可以打完收工,结果看到页面长这个样子:

image.png

为啥伪元素盖在了主体元素上面?赶紧调整一下 zIndex:

.fourth-process-section-step::before {
    ...
    z-index: -999;
}

发现还是不起作用。后面调小了盒子的 padding 后,发现 Analyzing your product... 这段文字确实盖在伪元素上面:

image.png

研究发现,单纯调整层级并不能改变背景图片和边框的位置(盒子内部元素 > 伪元素 > 背景和边框),所以只能调整 dom 结构:

思路就是不让伪元素的主体元素和需要设置背景图和边框的是一个元素

<section className='process-section-step'>
   <div className='process-section-step-content'>
      <Title level={4}>Analyzing your product...</Title>
   </div>
</section>

然后写 css:

.fourth-process-section-step {
  position: relative;
}

.fourth-process-section-step>.fourth-process-section-step-content {
  position: relative;
  display: flex;
  width: 400px;
  padding: 36px;
  align-items: center;
  gap: 10px;
  border-radius: 20px;
  border: 4px solid rgba(253, 224, 218, 0.84);
  background: linear-gradient(180deg, rgba(255, 255, 255, 0.35) 0%, rgba(255, 255, 255, 0.70) 100%);
  backdrop-filter: blur(14px);
}

.fourth-process-section-step::before {
  content: '';
  position: absolute;
  top: -30px;
  left: -35px;
  width: 70px;
  height: 70px;
  border-radius: 50%;
  border: 5px solid #FFD813;
  flex-shrink: 0;
  background: radial-gradient(106.67% 106.67% at 50% 15.15%, rgba(255, 242, 0, 0.90) 0%, #FFB006 91.67%);
  opacity: 0.7;
}

这样设置,整个背景图和边框就变成了主体元素的子元素了,自然会盖在伪元素上方。

运行发现已经可以了:

image.png

有时候工作上遇到问题解决不了,偶尔换个方向,往往有奇效。基于已有的规律换个方向来迎合这个规律,会让困难的问题变得简单。