How to write this pseudo class selector (last-child) for my nav menu?

Hello,
I’m trying to have a right margin of 0 for the last list item in my #homeNav element. I tried the “last-child” pseudo class selector but it is not doing anything.

The url for this is: http://ogmda.com/test/

I have the code in a css file called custom.css with the following rules:

#homeNav ul li {
	margin: 0;
	padding: 0;
	list-style: none;
	background: red;
	float: left;
}

#homeNav li a {
	display: block;
	line-height: 2em; /* centers the text vertically within the block */
	padding: 0 1em;
	margin-right: 8em;
}

#homeNav > li:last-child {
	margin-right: 0;	
}

Why can’t I get my right margin to set to 0? I want to keep the padding, just not the right margin on the last link. Thank you.

Your code is removing margin from a <li>, but the margin is applied to the <a>.

Well, I added:

#homeNav > li:last-child a {
	margin-right: 0;	
}

And it didn’t work…

Remove the child selector.


#homeNav li:last-child a {
    margin-right:0;
}

Unless you’re using IE8, it should work. :slight_smile:

Checking your online code, you haven’t actually added the a at the end of your rule yet.


<nav id="homeNav" class="clearfix">
    <ul>
        <li>
        <li>
        <li>
        <li>
    </ul>
</nav>

The <li> is not a child of #homeNav. :slight_smile:

Note: I have not uploaded my changes to the server, I’m currently working on this locally. With that said…

Aha! Thanks! I fixed it to:

 

#homeNav[B] ul[/B] > li:last-child a {
	margin-right: 0;
}


That worked! However, I still don’t quite understand why the pseudo class did not work as:


#homeNav ul > li:last-child {
	margin-right: 0;
}

I removed the “a” from that. Why does it matter if it has the a in it since we’re just concerned about removing the right margin from the last <li>? Why doe sit matter if we have “a” selector in the declaration?

Because the margin you are trying to remove is on the <a>, not on the <li>. There is no margin on the LI to remove.

Message #2… The margin is applied to the anchor, not the list item.

Off Topic:

ninja’d by Ralph :slight_smile:

Hey guys, that made absolute sense! YOu made it so easy for me to understand. Thanks again!