Remove margin in last child

My code here:

HTML

<nav id="pages">
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Donate</a></li>
        <li><a href="#">Video</a></li>
        <li><a href="#" class="last">Contact</a></li>
    </ul>
</nav>  <!-- end pages -->

CSS

#pages{
    position: absolute;
    right: 0;
    top: 70px;

    ul li{
        float: left;
        margin-right: 5px;

        a{
            color: @link-color;
            display: block;
            padding: 0 10px;
            border-radius: 5px;
            font-weight: bold;
        }
    }
}

.last{
    margin-right: 0;
}

I add class "last" to last child to remove margin but not effected. I don't use :last-child because it will not with IE6 or IE7. Hope someone help?

Answers


Try this:-

.last { margin-bottom: 0 !important; margin-right: 0 !important; }

There is no need to add a class "last" the best practice to do this and not write a lot of code would be:

#pages li:last-child{
    margin-right: 0px;
}

This way, you don't have to create any class last or anything. The css will look in the id pages, the last li (last-child) and will make it with margin-right of 0.


In your example it is the li that has the right margin but you have applied the class to the anchor link.

Your exiting CSS will work if you change the HTML to

<li class="last"><a href="#">Contact</a></li>

You need to add the class to the <li> tag, not the <a> tag.


The output of this LESS based CSS will be one of this - I'm not sure which one, I'm not this familiar with LESS:

#pages > ul > li {
    margin-right: 50px;
}

#pages ul li {
    margin-right: 50px;
}

The class .last is defined outside of this hierarchy. The problem is, that it's "only" a class and will therefore always have a lower precedence than the rule with the id #pages.

So either you define it fully qualified like this:

#pages ul li.last {
    margin-right: 0;
}

Or you add it inside the other definition:

#pages {
    ul li {}
    ul li.last { margin-right: 0; }
}

Demo

Try before buy


Change your CSS to

nav#pages ul li.last {
    margin-right: 0px;
}

and your HTML to:

<li class="last"><a href="#">Contact</a></li>

You can use :not(:last-child) to exclude the last child. So, for your example, you would have:

nav#pages ul :not(:last-child) {
    margin-right: 5px;
}

This will apply a margin-right: 5px to all but the last <li> ... </li>.

Checkout the jsfiddle example.


Need Your Help

Using a static MSVC 2010 libary (.lib) with MinGW?

mingw static-libraries visual-studio-2010 .a .lib

Since a few WIN32 related things didn't quite work using MinGW, I decided to create a small static library with MSVC 2010 and link it with MinGW afterwards. However, I am currently looking for a t...

How to create a list of properties for an item? LinkedList, ArrayList, Files?

java

I am not sure if this is a correct question for stackoverflow but I will try it anyhow.