Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

applying css for only parent but not to children

Tags:

html

css

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.

like image 426
Robz Avatar asked May 28 '13 08:05

Robz


People also ask

How does CSS choose parent to child?

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.

How do I skip the first child in CSS?

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 .

Can I use parent CSS?

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.


1 Answers

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.

like image 131
Guffa Avatar answered Oct 10 '22 11:10

Guffa