Search code examples
htmlcssxhtml

Apply background color to li but not the nested ones


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!


Solution

  • 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.