【问题标题】:Css / Pseudo element ::before behind his container not workCss / Pseudo element ::before 在他的容器后面不起作用
【发布时间】:2017-08-11 22:39:14
【问题描述】:

我尝试做某事,但它根本不起作用。 这看起来很简单,我希望将:before 添加到具有背景的元素中,但每次我这样做时,::before 都会出现在容器前面。

    .container{
     position:relative;
     z-index:1;
     background:blue;
     border:1 px solid white;
   }

   .container::before{
      position:absolute;
      content:"";
      z-index:-1;
      top:-10px;
      left:-10px;
      width:calc(100% + 20px);
      height:calc(100% + 20px);
      background:red;
   }

【问题讨论】:

  • 你希望 ::before 去哪里?在容器的左侧、右侧还是后面?
  • 在容器后面..我简化了代码,但前面有一个我想放在它后面的渐变,这就是为什么他在位置顶部 -10px ,离开容器的 -10px (还有 calc )

标签: css css-selectors pseudo-element


【解决方案1】:

只需从.container 中删除z-index:1 属性

body {
 background-color: #eee;
}

.container{
 position:relative;
 background:blue;
 border:1 px solid white;

 width: 200px;
 height: 200px;
}

.container::before{
  position:absolute;
  content:"";
  z-index:-1;
  top:-10px;
  left:-10px;
  width:calc(100% + 20px);
  height:calc(100% + 20px);
  background:red;
}
<body>

  <div class="container"></div>

</body>

【讨论】:

  • 非常感谢 :) 听起来合乎逻辑是的..但是如果(以我为例),身体有背景,你同意我之前的意志在身体后面,对吧?这意味着我需要另一个容器父级,其 z-index 优于主体?
  • 我刚刚更新了我的答案。如您所见,主体具有灰色背景:)
  • 对不起,我以为我昨天已经发布了最后一个答案,但我没有......所以,这是一篇关于 z-index 和堆栈上下文化的完整文章,因为它可能比它更复杂出现在:philipwalton.com/articles/what-no-one-told-you-about-z-index 另外,如果是,别忘了设置这个问题来解决:)
猜你喜欢
  • 2021-12-25
  • 2014-10-08
  • 2021-07-21
  • 2015-09-27
  • 2014-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多