Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select the first level of children (li) from ul

Tags:

html

css

Given the following structure, I want to select the first level of children (li) from the list (ul), but not the nested list.

ul.list > li {
  background-color: red;
}
<ul id="list" class="list">
   <li>first level</li>
   <li>first level</li>
   <li>
      <h1></h1>       
      <div>
         <ul>
            <li>second level</li>
            <li>second level</li>
         </ul>
      </div>
   </li>
   <li></li>
</ul>

(JSFiddle)

But that selects also the items (li) inside the div.

I want to select the first level of children (li) using only ONE css RULE. How?

like image 600
Marco Avatar asked Jan 29 '16 21:01

Marco


4 Answers

css does not have a selector that would allow you to specify that all/none of the ancestor elements must match certain critieria (i.e. not be a list), you would need xpath for that.

but what you can do is the following:

ul > li {
  // top level list item styles here
}

li ul > li {
  all: initial;
  // nested item styles here
}

See MDN all for documentation on resetting styles. You can also selectively unset specific properties.

like image 136
the8472 Avatar answered Oct 14 '22 15:10

the8472


you need to identify your first ul:

<ul class="my-list">
   <li></li>
   <li></li>
   <li>
      <h1></h1>       
      <div>
         <ul>
            <li></li>
            <li></li>
         </ul>
      </div>
   </li>
   <li></li>
</ul>

then select it with ul.my-list>li

like image 38
Yukulélé Avatar answered Oct 14 '22 14:10

Yukulélé


CSS

ul li div ul li { 
  /* Your styles here to override parent (if they are over 70% the same) */ 
}
like image 30
Dirk Jan Avatar answered Oct 14 '22 15:10

Dirk Jan


You can add a class to the <li>s which contain second-level content and then exclude them from the main CSS query using the :not pseudo-class

ul.list > li:not(.level2) {
  background-color: red;
}
<ul class="list">
   <li>first level</li>
   <li>first level</li>
   
   <li class="level2"> first level with nested content
      <h1>some title</h1>       
      <div>
         <ul>
            <li>second level</li>
            <li>second level</li>
         </ul>
      </div>
   </li>
   
   <li>first level</li>
</ul>
like image 26
Aziz Avatar answered Oct 14 '22 14:10

Aziz