Reputation: 642
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/
Upvotes: 2
Views: 1044
Reputation: 40970
You need to use Child selector for selecting the last element(div) of li
.
ul li:last-child > div{
background-color: red;
}
Upvotes: 3
Reputation: 4285
It's because you are targeting a div
with your :last-child
usage.
ul li {
background-color: green;
}
ul li:last-child {
background-color: red;
}
Fiddle: http://jsfiddle.net/5Vm58/19/
Upvotes: 0
Reputation: 298256
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/
Upvotes: 3