li:last-child formatting an inner div

Warning... not the sharpest tool in the CSS toolbox here...

I'm trying to write a tree control using ULs... and stuck on a CSS issue. To simplify the question, I boiled down the example to something that might not make sense, but the essence of the CSS issue is as simple as possible.

Consider this html:

<ul>
    <li><div>should be green :)</div>
        <ul>
            <li><div>should be green :)</div></li>
            <li><div>should be red :)</div></li>
        </ul>
    </li>
    <li><div>should be red :)</div>
        <ul>
            <li><div>should be green !!!!!!!!!!!!</div></li>
            <li><div>should be red :)</div></li>
        </ul>
    </li>
</ul>

and this CSS:

ul li{
    background-color: green;
}

ul li:last-child div{
    background-color: red;
}

The one item that says:

<li><div>should be green !!!!!!!!!!!!</div></li>

Appears red instead of green!!!!!

Since the div that contains it is contained in an LI that is NOT the last in the list, I expected it to use the normal selector instead of the last-child selector

Here is a fiddle for your reputation point seeking pleasure!

http://jsfiddle.net/dmd1214/5Vm58/16/

Answers


You need to use Child selector for selecting the last element(div) of li.

ul li:last-child > div{
    background-color: red;
}

JS Fiddle


Make your descendant selector a child selector:

ul li:last-child > div {
    background-color: red;
}

That way, it matches only the <div> elements that are children of that last <li> element.

Demo: http://jsfiddle.net/5Vm58/20/


Need Your Help

php - CURL HTTP Authentication at server side

php xml curl

i want to change xml value in php but don't change ....

Change style of an element when focus is another element

html css css-selectors

I need to change the style of a div when focus is on another div.I tried the following code but didn't work

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.