【问题标题】::not(:last-of-type) not working for class:not(:last-of-type) 不适用于课堂
【发布时间】:2014-05-15 09:27:10
【问题描述】:

为什么:not(:last-of-type) 在以下情况下不起作用?我该如何解决?

JSFiddlehttp://jsfiddle.net/C23g6/589/

HTML:

<div class="comment">This is Red</div>
<div class="hello">------------------</div>
<div class="comment">This is Red</div>
<div class="hello">------------------</div>
<div class="comment">Shouldn't be Red</div>
<div class="hello">------------------</div>

CSS:

.comment:not(:last-of-type) {
    color: red;
}

【问题讨论】:

  • :last-of-type 不适用于课程。它适用于元素类型。由于所有元素都是divs,所以显然不行。
  • 在这种情况下我可以使用其他东西吗?
  • 我自己找到了解决方案。我只是将 div 更改为类为 .comment 的跨度,并在 CSS 中创建了 .comment display: block
  • div:not(:nth-last-of-type(2)){color: red}

标签: css css-selectors


【解决方案1】:

如前所述,原因是:last-of-type 匹配作为其元素类型的最后一个兄弟元素的元素,在本例中为div。由于最后一个div 不是最后一个.comment,因此不匹配。

the first element of a class 不同,没有办法使用纯CSS 来匹配类的last 元素,即使使用覆盖也不行。您应该使用有关现有结构的信息来创建与您正在寻找的元素匹配的选择器,例如:

.comment:not(:nth-last-child(2))

否则,在最后一个 .comment 中添加一个额外的类名并将其排除,或者以其他方式更改结构本身以满足您的需求。

【讨论】:

    【解决方案2】:

    如果你的结构永远不会改变,那么:

    div {
        color:red;
    }
    :nth-last-of-type(2) {
        color: black;
    }
    

    这将是一种简单的方法:DEMOdemo 2

    :not() 仍有限制。

    【讨论】:

      猜你喜欢
      • 2016-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-07
      • 2021-12-20
      • 1970-01-01
      • 2017-04-22
      相关资源
      最近更新 更多