2017-01-24 17 views
1

我有问题::nth-child(n):before在用?:nth-​​child(n):之前是不工作?

所以,我使用SASS。
为什么下面的代码不工作?

@for $i from 1 through 4 
    .block:nth-child(#{$i}):before 
     background: url(../../img/block-img-#{$i}.jpg) 
     background-size: cover 

它编译成:

.content .cnt1 .block:nth-child(1):before { 
    background: url(../../img/block-img-1.jpg); 
    background-size: cover; 
} 

.content .cnt1 .block:nth-child(2):before { 
    background: url(../../img/block-img-2.jpg); 
    background-size: cover; 
} 

.content .cnt1 .block:nth-child(3):before { 
    background: url(../../img/block-img-3.jpg); 
    background-size: cover; 
} 

.content .cnt1 .block:nth-child(4):before { 
    background: url(../../img/block-img-4.jpg); 
    background-size: cover; 
} 

所有迪尔斯到的图像是真实的。但它不工作:( 我做错了吗?

+2

你也可以举一个相应的HTML的例子吗? – Sirko

+1

您还需要将'content:'''添加到before-rule中,我想您需要为该元素设置宽度和高度,否则背景可能会应用于0px x 0px元素。 –

+1

为什么在每个规则中设置背景大小:封面?这似乎是完全膨胀CSS的快速方法。 – BoltClock

回答

1

就其本身而言,一个::before伪元素是不可见的,你还需要给它一个display财产,以及一些内容,否则,也不会节目。

现在你没有提供的HTML,但如果我可以推测,它只是一堆嵌套的div时,需要额外的CSS看起来是这样的。

.content .cnt1 .block::before { 
    display:block; content:''; 
    height:200px;    /* a height, any height */ 
} 

或者一个更完整的例子:(不要介意背景图片)

.content .cnt1 .block::before { 
 
    display:block; content:''; 
 
    height:200px;    /* a height, any height */ 
 
} 
 
.content .cnt1 .block:nth-child(1)::before { 
 
    background: url(http://images.clipartpanda.com/number-clipart-niXxEn7iB.jpeg); 
 
    background-size: cover; 
 
} 
 

 
.content .cnt1 .block:nth-child(2)::before { 
 
    background: url(http://images.clipartpanda.com/clipart-numbers-9czE7pRpi.png); 
 
    background-size: cover; 
 
} 
 

 
.content .cnt1 .block:nth-child(3)::before { 
 
    background: url(http://images.clipartpanda.com/creation-clip-art-RTAE8d8TL.jpeg); 
 
    background-size: cover; 
 
} 
 

 
.content .cnt1 .block:nth-child(4)::before { 
 
    background: url(http://images.clipartpanda.com/number-clip-art-RcA6Axgji.png); 
 
    background-size: cover; 
 
}
<div class="content"> 
 
<div class="cnt1"> 
 
<div class="block"></div> 
 
<div class="block"></div> 
 
<div class="block"></div> 
 
<div class="block"></div> 
 
</div> 
 
</div>

顺便说,与一个结肠:before符号已被弃用;首选的方法是::before

或者,如果您想使用:before与旧版浏览器兼容,那么请注意,您也不能使用background-size
也就是说,使用:before的唯一原因是如果您想与IE8兼容。 :before适用于IE,::before不适用。
但是因为IE8不支持background-sizenth-child(),所以你不会得到这个特殊的例子在IE8中工作,所以没有必要打扰。

+0

噢!我做的比...更多时间,我不知道问题在哪里..非常感谢! – RamoFX

+0

我怀疑是否使用单个冒号排除了使用“背景大小”。另外,为什么我需要添加一个显式的'display'属性? –

+1

@torazaburo:Lister先生说[世界上唯一只支持单冒号语法的浏览器不支持背景大小](http://stackoverflow.com/a/28527928),所以使用如果您要依赖背景大小,那么兼容性的单分号语法就毫无意义。 display:block声明是必需的 - 除非声明已经存在于其他地方或存在其他声明导致它们被阻塞 - 因为伪元素没有默认显示值,所以它们采用初始值,内联和高度属性将不适用。 – BoltClock