如何在div之前和之后显示内容

时间:2017-02-13 11:08:36

标签: html css

我希望&:before&:after的内容显示在div.first之外以及之前和之后。

我认为最好的方法是使用上面的css,但它仍然出现在div内,我使用的是错误的方法还是其他的?

Jsfiddle:https://jsfiddle.net/1uuL3sf6/1/

HTML

<div class="first">

</div>

CSS

.first
{
  width: 100%;
  height: 500px;

  background-color:red;

  &:before
  {
    content:"before";
    width: 100%;
    height: 20px;
  }

   &:after
  {
    content:"after";
    width: 100%;
    height:20px;
  }

}

3 个答案:

答案 0 :(得分:1)

伪元素:beforeafter不会在其父元素之前和之后创建内容。它们在实际内容之前和之后插入。

  

伪元素完全符合这个词所暗示的含义。它会创建一个虚拟元素,并在您定位的元素内容之前或之后插入它。

来自“Learning To Use The :before And :after Pseudo-Elements In CSS

这就是为什么它们总是显示在父母的框内。

但是,作为示例,您可以使用绝对定位将伪元素移出框中:

&:before {
    content:"before";
    position: absolute;
    top: -20px;
    width: 100%;
    height: 20px;
}

但你也可以float将它们显示为block,以达到理想的效果。

<强>演示

Try before buy

答案 1 :(得分:0)

&#13;
&#13;
.first {
  width: 100%;
  height: 500px;
  
  background-color:red;
 } 
  .first::before
  {
    content:"before";
   
  }
  
   .first::after
  {
    content:"after";
    
  }
  
&#13;
<div class="first">
</ br>  This is your first div. </ br>  
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

这是一个解决方案:https://jsfiddle.net/e8qtoxL9/

.first
{
  width: 200px;
  height: 200px;
  margin: 0 auto;
  background-color:lightgreen;
  position: relative;

  &:before
  {
    content:"before";
    width: 100%;
    height: 20px;
    display: block;
    background: lightblue;
    left: -100%;
    top: 0;
   position: absolute;
 }

   &:after
  {
    content:"after";
    width: 100%;
    height:20px;
    display: block;
    background: lightblue;
    left: 100%;
    top: 0;
   position: absolute;
  }
}
相关问题