tags:

views:

48

answers:

7

I have nested ul/li's and the problem is that if you add a background color to the top li, because there are nested items within it the whole list appears to have this background color rather than just the top li (I assume this is because it's extending the height of the top li).

Is it possible to only apply the background color to the top li?

I hope this makes sense!

A: 

well you can always apply a different background colour to the child li's.

Ramuns Usovs
A: 

use jquery and give a special class to the first li

`$("ul li:first")`.addClass('special_bg')

= get only the first <-li-> element of the <-ul->

Haim Evgi
A: 

This depends on your CSS. You could define a top-level li class and use that to set the background colour.

Dan Iveson
A: 

Children always inherit attributes from the parents; that's why it's called Cascading Style Sheets.

I suggest to give all li elements a default background color and just override it for the top level elements (for example with a special class).

Aaron Digulla
A: 

What I understand is that you have a UL with LI in it (let's call it 'parent'), and that LI also has a UL with LI (let's call them child) in it? You apply the background to the parent and it's also visible under the child?

As the child are located INSIDE the parent they must change his height, so the background is bigger than tought, there is 2 way to block that, you could (as mentionned earlier) put another background the the child, or you could put something like a SPAN inside the parent and put the background on the SPAN instead of the LI.parent.

Dominique
+1  A: 

You're speaking of the top li, but I think you mean the root li, which has child elements containing li elements as well. In that case, you can set the background color as follows:

.myroot>ul>li { background-color: Yellow }

Note: the sample above requires a wrapper element (usually a DIV) with the class name "myroot".

See this article for more about CSS child selectors.

Prutswonder
+1  A: 

There is the relationship selector > which means "immediate children":

ul > li {
    background-color: <your color>;
}

but I have had problems with cross-platform compatibility while using it. What you can also do is set up multiple levels of rules:

ul li {
    background-color: <your color>;
}

ul li li {
    background-color: none;
}
amphetamachine
the second option is better since IE6 doesn't support the ">" child selector
Jonathan Day
@Jonathan That is exactly what I meant by "but I have had problems with cross-platform compatibility while using it."
amphetamachine
no worries, I thought you were referring to Windows vs Linux vs Mac.
Jonathan Day