3

JsFiddle

My problem is that when using the pseudo code :last-child I expect the li containing E to be affected by the style but it's the last li in .subNav which is affected.

I've tried those(below), but nothing works.

nav ul:first-child li:last-child {border: none;padding-right: 0;}
nav ul:not(.subNav) li:last-child {border: none;padding-right: 0;}

How to get the main ul's last li affected?

Xlander
  • 1,331
  • 12
  • 24

5 Answers5

4

There is a div after the last li. Therefore, it isn't the last child. You could use :last-of-type to target the last li :

nav ul li:last-of-type {border: none;padding-right: 0;}

DEMO

web-tiki
  • 99,765
  • 32
  • 217
  • 249
1

Remove the div which is inside ul. Adding any tags directly inside ul is not valid.

Place it inside li or remove it if not really necessary.

Otherwise your css selector is just fine.

<nav>
    <ul>
        <li><a href="#">A</a></li>
        <li class="B">
            <a href="#">B</a>
            <ul class="subNav">
                <li><a href="#">F</a></li>
                <li><a href="#">G</a></li>
                <li><a href="#">H</a></li>
                <li><a href="#">I</a></li>
            </ul>
        </li>
        <li><a href="#">C</a></li>
        <li><a href="#">D</a></li>
        <li><a href="#">E</a></li>
    </ul>
</nav>

DEMO

Sowmya
  • 26,684
  • 21
  • 96
  • 136
1

That's not the last child, you can use nth-last-child:

nav ul > :nth-last-child(2)

Or, use last-of-type:

nav ul > li:last-of-type

But I would recommend you to use as @Sowmya answer which is symantically correct.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
1

Your selector is logically correct, but the problem is that the li is not the last child of its parent ul, because there's that div.clear

<ul>
    <li><a href="#">A</a></li>
    <li class="B"><a href="#">B</a>
        <ul class="subNav">
        ...
        </ul>
    </li>
    <li><a href="#">C</a></li>
    <li><a href="#">D</a></li>
    <li><a href="#">E</a></li>
    <div class="clear"></div>
</ul>

In this case nav ul li:last-child doesn't match anything because the li is not the last child. You should use nav ul li:last-of-type to match the last li element.

Note that uls only allow li as children, so having a div contained in an ul is wrong. If you remove that div.clear your code will work.

Alessandro Vendruscolo
  • 14,493
  • 4
  • 32
  • 41
1

The pseudo class :last-child only triggers if the element is the last child in the parent.

In your case, there is a div within your ul which is not allowed anyway. Remove it and use a clearfix of some kind on the parent ul.

Community
  • 1
  • 1
c_k
  • 321
  • 1
  • 6