首页 > 解决方案 > ":last-child" 和 ":not(:last-child)" 之间的不同行为

问题描述

我有以下html代码:

<nav>
  <ul>
    <li>Text1</li>
    <li>Text2</li>
    <li>Text3</li>
  </ul>
</nav>

使用:

nav :last-child {
   text-transform: uppercase;
}

结果是:

使用:

nav li:last-child {
   text-transform: uppercase;
}

结果是:

使用时:

nav :not(:last-child) {
   text-transform: uppercase;
}

结果是:

为什么 ":not(:last-child)" 不需要 "li" 来定位最后一个孩子?谢谢。

标签: htmlcsscss-selectors

解决方案


nav :last-child包括您的单个<ul>元素。由于只有一个,它是一个:last-child。所以它适用text-transform: uppercase;于所有如果它的内容,在这种情况下,所有三个<li>元素。它被应用到最后<li>,因为它也是一个:last-child。为了更清楚地看到这一点,这里有一个包含两个<ul>元素的示例。

nav :last-child {
   text-transform: uppercase;
}
<nav>
  <ul>
    <li>This is not a last-child, and parent not a last-child</li>
    <li>This is not a last-child, and parent not a last-child</li>
    <li>Last-child of li in this section</li>
  </ul>
  <ul>
    <li>Parent ul of these li's is a last-child</li>
    <li>So all three li's</li>
    <li>Are uppercase</li>
  </ul>
</nav>

nav li:last-child特定于 only li,因此它只设置最后一个<li>.

nav li:last-child {
   text-transform: uppercase;
}
<nav>
  <ul>
    <li>Only applies to li's</li>
    <li>So ul has no style applied</li>
    <li>But this li is a :last-child</li>
  </ul>
  <ul>
    <li>Only applies to li's</li>
    <li>So ul has no style applied</li>
    <li>But this li is a :last-child</li>
  </ul>
</nav>

最后,nav :not(:last-child)适用于:不是最后一个孩子的任何事情

nav :not(:last-child) {
   text-transform: uppercase;
}
<nav>
  <ul>
    <li>This ul is <b>not</b> a :last-child</li>
    <li>So all of its content</li>
    <li>will be uppercase</li>
  </ul>
  <ul>
    <li>This ul <b>is</b> a :last-child</li>
    <li>But these first two li's are not</li>
    <li>So they are uppercase</li>
  </ul>
</nav>


推荐阅读