Z-index没有工作:之前& :后

时间:2016-04-21 20:09:09

标签: html css z-index

我正在尝试像链接图像中的那样制作一个色带,但是当我使用z-index将色带的主要部分后面的边缘发送时,它完全消失在页面背景颜色的后面。任何人都可以告诉我我的代码有什么问题吗?ribbon image

HTML:

<!DOCTYPE html>
<html>
    <head>
        <title>Newsletter signup</title>
        <link href="style.css" rel="stylesheet">

    </head>
    <body>
        <div class="container">
          <div class = "header">
            <h1 class = "logo">skillcrush</h1>
              <div class="ribbon">
                <p>the delightful way to learn</p>
              </div>
           </div><!--header-->
        </div><!--container-->
    </body>
</html>

CSS:

.container-body{
  margin: 0 auto;
  width:1200px;
  height:702px;
  background-color:#fff0da;
  z-index: auto;
}

.ribbon{
  text-align: center;
  position: absolute;
  left:0;
  right:0;
  top:120px;
  margin-left: auto;
  margin-right: auto;
  font-size:16px;
  background-color:#f6515d;
  height:28px;
  width:260px;
  color:rgb(255, 240, 218);
  border: solid #fff0da 2px;
  z-index: 2;
}

.ribbon:before
{
  content: ' ';
  position:absolute;
  width: 30px;
  height: 0;
  left: -30px;
  top: -10px;
  border-width: 20px 10px;
  border-style: solid;
  border-color: #f6515d #f6515d #f6515d transparent;
  z-index: 1;


}
.ribbon:after
{
  content: ' ';
  position:absolute;
  width: 30px;
  height: 0;
  right:-30px;
  top: -10px;
  border-width: 20px 10px;
  border-style: solid;
  border-color: #f6515d transparent #f6515d #f6515d;
  z-index: 1;
}

1 个答案:

答案 0 :(得分:2)

您需要在.container-body上建立新的堆叠上下文。

.container-body { z-index: 1; position: relative; /* ... */ }

然后对伪元素使用负z-indexing:

.ribbon { /* no z-index, ... */ }
.ribbon:before, .ribbon:after { z-index: -1; /* ... */ }

以下是一个完整的例子:

.container-body{
  margin: 0 auto;
  width:1200px;
  height:702px;
  background-color:#fff0da;
  z-index: 1;
  position: relative;
}

.ribbon{
  text-align: center;
  position: absolute;
  left:0;
  right:0;
  top:120px;
  margin-left: auto;
  margin-right: auto;
  font-size:16px;
  background-color:#f6515d;
  height:28px;
  width:260px;
  color:rgb(255, 240, 218);
  border: solid #fff0da 2px;
}

.ribbon:before
{
  content: ' ';
  position:absolute;
  width: 30px;
  height: 0;
  left: -30px;
  top: -10px;
  border-width: 20px 10px;
  border-style: solid;
  border-color: #f6515d #f6515d #f6515d transparent;
  z-index: -1;


}
.ribbon:after
{
  content: ' ';
  position:absolute;
  width: 30px;
  height: 0;
  right:-30px;
  top: -10px;
  border-width: 20px 10px;
  border-style: solid;
  border-color: #f6515d transparent #f6515d #f6515d;
  z-index: -1;
}
<div class="container-body">
  <div class="ribbon">Test</div>
</div>