Pseudo elements allow us to target elements that are not explicitly set in the DOM. Using ::before ::after
we can actually create and manipulate elements in the DOM that do not impact the content. While ::first-letter ::first-line ::selection ::placeholder
allow us to target elements that do not have a specific DOM element.
Can someone explain why the following selector selects all but the last item? Thanks
:nth-last-child(n+2)
Can someone explain why the following selector selects all but the last item? Thanks
:nth-last-child(n+2)
We can break it down. last-child
means it's starting from the bottom. n+2
is the equation it uses (counting up from the bottom). n
starts with 0
, but the first list item is 1
. So the first value is 0+2
which equals 2
so the rule applies to the second from the bottom (skipping the very last item which is 1
). The next value is 1+2
so the 3rd from the bottom. Continued until all the items have the rules applied, except for the very last one.
That make sense. Thanks for the explanation Garth!
I was confused about this too, thanks for the explanation.
You can also achieve the same effect like this :nth-child(n + 2)::before
You can also achieve the same effect like this :nth-child(n + 2)::before
Sure. You either add a divider after the element to all but the last, or add one before the element to all but the first. You could also use li:not(:first-child)::before
or li:not(:last-child)::after
Multiple ways to achieve the same goal.