【问题标题】:CSS :before is appearing :after [duplicate]CSS :before 出现 :after [重复]
【发布时间】:2019-03-20 12:04:17
【问题描述】:

我有一个要显示的框,我希望在框后面显示一个背景以覆盖屏幕上剩余的内容。 Box 和 Background 是固定位置的,并且每个的 z-index 都按照您的预期设置,但背景总是覆盖盒子?

.box {
  position: fixed;
  width: 100px;
  height: 100px;
  top: 100px;
  left: 100px;
  background-color: yellow;
  border: 10px solid green;
  z-index: 1;
 }
 .box:before {
  content: '';
  position: fixed;
  width: 300px;
  height: 300px;
  top: 150px;
  left: 150px;
  background-color: tomato;
  z-index: -1;
 }
<div class="box"></div>

【问题讨论】:

标签: html css


【解决方案1】:

您正在使用position:fixed,然后将您的:before 放置在距顶部150 像素和距左侧150 像素的位置,因此在您的.box 之后是100 像素宽和100 像素高并且定位在距离左侧 100px 和距离顶部 100px 的位置,也是固定位置。

如果你在你的:after 上使用position:absolute,它将相对于它的父 div 定位。例如:

.box {
  position: fixed;
  width: 100px;
  height: 100px;
  top: 100px;
  left: 100px;
  background-color: yellow;
  border: 10px solid green;
  z-index: 1;
 }
 .box:before {
  content: '';
  position: absolute;
  width: 100px;
  height: 100px;
  top: 0px;
  left: -110px;
  background-color: tomato;
  z-index: -1;
 }
<div class="box"></div>

编辑:在得到 Amaury Hanser 的评论后,我添加了第二个 sn-p(因为我不知道是不是原版的投了赞成票)。

要将:before 置于.box 的“下方”,就z-index 而言,您可以将:before:after 结合使用:

.box:before {
  content: '';
  position: fixed;
  width: 100px;
  height: 100px;
  top: 100px;
  left: 100px;
  background-color: yellow;
  border: 10px solid green;
  z-index: 1;
 }
 .box:after {
  content: '';
  position: absolute;
  width: 300px;
  height: 300px;
  top: 150px;
  left: 150px;
  background-color: tomato;
  z-index: 0;
 }
<div class="box"></div>

简单地说,伪元素很像子/父元素。除非父元素没有指定 z-index,否则子元素的 z-index 不能低于父元素。此外,一些position CSS 规则给出了“默认”z-index,没有孩子可以“突破”它落后。

【讨论】:

  • 我认为他希望 :before 元素成为 behind 主要元素。与左和上无关。这就是他谈论 z-index 的原因。
猜你喜欢
  • 2011-02-19
  • 2012-04-24
  • 2022-10-24
  • 2013-07-20
  • 2011-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多