Different behaviour between ":last-child" and ":not(:last-child)"

Abs*_*ner 7 html css css-selectors

I have the following html code:

<nav>
  <ul>
    <li>Text1</li>
    <li>Text2</li>
    <li>Text3</li>
  </ul>
</nav>
Run Code Online (Sandbox Code Playgroud)

Using:

nav :last-child {
   text-transform: uppercase;
}
Run Code Online (Sandbox Code Playgroud)

Result is:

  • TEXT1
  • TEXT2
  • TEXT3

Using:

nav li:last-child {
   text-transform: uppercase;
}
Run Code Online (Sandbox Code Playgroud)

Result is:

  • Text1
  • Text2
  • TEXT3

While using:

nav :not(:last-child) {
   text-transform: uppercase;
}
Run Code Online (Sandbox Code Playgroud)

Result is:

  • TEXT1
  • TEXT2
  • Text3

Why ":not(:last-child)" doesn't need "li" to target the last child? Thanks.

chr*_*ris 9

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

nav :last-child {
   text-transform: uppercase;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

nav li:last-child专用于只li的,所以它只是风格的最后<li>

nav li:last-child {
   text-transform: uppercase;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

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

nav :not(:last-child) {
   text-transform: uppercase;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)