在scss中使用&:first-of-type与仅使用:first-of-type有什么区别吗

时间:2018-08-30 20:20:30

标签: sass

使用嵌套在apple类中的&:first-of-type与仅嵌套在all-fruits类中的:first-of-type有什么区别吗?因为它们都通过使苹果色为红色来给出相同的结果。如何知道何时使用它们?

html:

<div class="all-fruits">
    <p class="fruit apple">Apple</p>
    <p class="fruit strawberries">Strawberries</p>
</div>

css:

$apple: red;



.all-fruits{ 
  margin-left: 200px;
  margin-top: 100px;
  .apple {
    color: $apple;
  }
  :first-of-type {
    font-size: 100px;
  }
}

vs

.all-fruits{
  margin-left: 200px;
  margin-top: 100px;
  .apple {
    color: $apple;
     &:first-of-type {
       font-size: 100px;
     }
  }
}

1 个答案:

答案 0 :(得分:1)

  

使用&:first-of-type与仅使用:first-of-type有什么区别

是的,两者之间有差异,在某些情况下可能会有很大差异。看看从您的SASS示例生成的CSS:

  
/* :first-of-type example */

.all-fruits :first-of-type {
  font-size: 100px;
}

/* &:first-of-type example */

.all-fruits .apple:first-of-type {
  font-size: 100px;
}

在第一个示例中,您说的是“将所有从.all-fruits元素继承的元素的font-size设置为100px,假定它是该类型的第一个元素”。因此,如果您将任何非段落元素添加到.all-fruits div中,它的字体大小也将为100px。考虑以下示例:

   
<div class="all-fruits">
  <p class="fruit apple">Apple</p>
  <p class="fruit strawberries">Strawberries</p>
  <span>Yummy!</span>
</div>

使用.all-fruits :first-of-type时,跨度也将具有100px的字体大小,而.all-fruits .apple:first-of-type将确保只有那些类型第一且具有.apple类的元素才能获得100px字体。

  

因为它们都给出了相同的结果……如何知道何时使用它们?

在某些特定情况下,给出相同的结果都不是假设两者都对工作同样有利的借口。我相信以下CSS将为您提供与当前HTML相同的结果:

  
.all-fruits {
  margin-left: 200px;
  margin-top: 100px;
}
.all-fruits .apple {
  color: red;
}
*:not(:last-of-type) {
  font-size: 100px;
}

但是,这并不意味着我的:not选择器完全没有问题。实际上,使用该选择器将是一个糟糕的决定。

尽管很难预测当前HTML的所有可能添加方式并编写100%面向未来的CSS,但通常不是一个好主意,而是通过类而不是非常通用或通用的选择器来应用样式。

对于您来说,.apple:first-of-type:first-of-type似乎是更好的选择。如果我对您的要求有更多了解,我还会考虑使用.fruit:first-of-type,因为它会增加列表中排在首位的所有水果的字体大小,而不仅仅是苹果。