如何使用after和before属性选择div的所有外侧

时间:2017-10-14 06:47:38

标签: html css html5 css3 css-selectors

请参阅我的HTML代码。

.new-div{
  width:200px;
  height:200px;
  border:1px solid orange;
  text-align:center;
}

.new-div::before{
content: "&nbsp";
position: absolute;
top: 0;
width: 100%;
z-index: 90;
background-color: gray;
left: 0;

}
.new-div::after{
content: "&nbsp";
position: absolute;
bottom: 0;
width: 100%;
z-index: 90;
background-color: gray;
left: 0;

}
 <div class="new-div">
  content
 </div>

这里我想使用after和before属性将new-div的所有外侧都设置为灰色。我怎么能得到这个。当iam使用之后和之前的属性我只能获得2面。

请参阅下图。我希望输出像这样。

enter image description here

1 个答案:

答案 0 :(得分:2)

我认为这和你想要的一样。

.new-div{
  width:200px;
  height:200px;
  border:1px solid orange;
  text-align:center;
  margin:0 auto;
  background-color:#fff;
}

.new-div::before{
content: "&nbsp";
position: absolute;
top: 0;
width: 100%;
z-index: -1;
height:100%;
background-color: gray;
left: 0;

}
.new-div::after{
content: "&nbsp";
position: absolute;
bottom: 0;
width: 100%;
z-index: 90;
background-color: gray;
left: 0;

}
 <div class="new-div">
  content
 </div>