:nth-child(n):以前不起作用?



我有问题::nth-child(n):before工作吗?

所以,我使用 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;
}

所有图像的目录都是真实的。但它不起作用:(我做错了什么?

::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中工作,所以没有必要打扰。