2017-02-13 97 views
0

我希望我的内容从&:before&:after出现在我的div.first之外和之前和之后。如何在div前后显示内容

我认为最好的方法是使用上面的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; 
    } 

} 

回答

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

谢谢,它的工作。对不起吃午饭:D。 –

0

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

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; 
    } 
}