I have an unordered list like this:
<div class="list"> <ul> <li> list1 <ul> <li>Sub list1</li> <li>Sub list2</li> <li>Sub list3</li> </ul> </li> <li> list2 <ul> <li>Sub list1</li> <li>Sub list2</li> <li>Sub list3</li> </ul> </li> </ul> </div>
I now want to apply CSS only for the first list but not its children ul
and li
. I've attempted the following:
.list ul li{ background:#ccc; }
...but the background color is applied to all lists. What should be done to change the CSS of only parent but not the children.
The element>element selector is used to select elements with a specific parent. Note: Elements that are not directly a child of the specified parent, are not selected.
I think :nth-child() will do the trick. This styles all of the p tags except for the first because it starts on the 2nd child. You could then style the first p tag separately with p:first-child .
There is currently no way to select the parent of an element in CSS, at least not a way that works across all browsers. If there was a way to do it, it would be in either of the current CSS selectors specs: Selectors Level 3 Spec.
Use the direct descendant operator >
for that:
.list > ul > li { ... }
The >
operator selects only elements that are direct children of the element(s) before it.
Note however, anything inside that list item will of course have the background of the list item despite not having any background color directly assigned to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With