last-of-type不起效果?

RainLucky
  • 413

如下代码所示,要对class值为children的第一个和最后一个背景色单独设置,为什么first-of-type有效果,last-of-type不起作用呢?
image.png

 <span class="parent">
    <span class="children">1</span>
    <span class="children">2</span>
    <span class="children">3</span>
    <span class="children">4</span>
    <span class="children">5</span>
    <span class="special">就是不一样</span>
  </span>
.children{
    display:inline-block;
    width:50px;
    height:50px;
    background:gray;
    &:first-of-type{
        background:pink;
    }
    &:last-of-type {
        background:yellow;
    }
}
回复
阅读 818
3 个回答
✓ 已被采纳

看了楼下的答案我发现我错了。哈哈哈哈


.children:last-of-type 需要同时满足

满足:.children

<span class="children">1</span>
<span class="children">2</span>
<span class="children">3</span>
<span class="children">4</span>
<span class="children">5</span>

满足::last-of-type

<span class="children">5</span>
<span class="special">就是不一样</span>

满足 :last-child

<span class="special">就是不一样</span>

满足 :nth-last-of-type(1)

<span class="children">5</span>
<span class="special">就是不一样</span>

问题常出现在 list 组件中,后面跟了一个加载更多,导致样式无法生效。解决办法就是给 children 做一个父级。。

last-child:先匹配所有兄弟元素中的最后一个,再看是否命中:last-child前面的条件

last-of-type:先根据标签名称(span)进行分组,再匹配分组中的最后一个元素(.special),再看是否命中:last-of-type前面的条件(.children,没有命中)

解决方案就是采纳答案里说的加个父级
image.png

 <span class="parent">
      <span>
      <span class="children">1</span>
      <span class="children">2</span>
      <span class="children">3</span>
      <span class="children">4</span>
      <span class="children">5</span>
      </span>
      <span class="special">就是不一样</span>
    </span>
宣传栏