Xlander
Xlander

Reputation: 1331

ul li:last-child affects the last li in the second ul

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?

Upvotes: 3

Views: 1734

Answers (5)

c_k
c_k

Reputation: 321

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.

Upvotes: 1

web-tiki
web-tiki

Reputation: 103790

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

Upvotes: 4

Alessandro Vendruscolo
Alessandro Vendruscolo

Reputation: 14875

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.

Upvotes: 1

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85575

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.

Upvotes: 1

Sowmya
Sowmya

Reputation: 26969

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

Upvotes: 1

Related Questions