I have the following html code:
<nav>
<ul>
<li>Text1</li>
<li>Text2</li>
<li>Text3</li>
</ul>
</nav>
Using:
nav :last-child {
text-transform: uppercase;
}
Result is:
Using:
nav li:last-child {
text-transform: uppercase;
}
Result is:
While using:
nav :not(:last-child) {
text-transform: uppercase;
}
Result is:
Why ":not(:last-child)" doesn't need "li" to target the last child? Thanks.
:not(:last-child) The :not() selector excludes the element passed to it from selection. The :last-child selector selects the last child. Combining these two above selector to excludes the last children (inner-div) of every parent div from the selection.
ul:not(:first-child) means literally "any ul element that is not first child of its parent", so it won't match even the 1st ul if it's preceded by another element ( p , heading etc.).
To select all the children of an element except the last child, use :not and :last-child pseudo classes. Example 1: This example creates a navigation menu separated by right border except the last element. Example 2: This example creates a navigation menu and uses some CSS property except the last element.
nav :last-child
includes your single<ul>
element. Since there is only one, it is a :last-child
. So it applies text-transform: uppercase;
to all if its contents, in this case, all three <li>
elements. It is also being applied to the last <li>
, because it is also a :last-child
. To see this more clearly, here is an example with two <ul>
elements.
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
is specific to only li
's, so it only styles the last <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>
And finally, nav :not(:last-child)
applies to anything that is :not a 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With