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?
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.
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
CSS
ul li div ul li {
/* Your styles here to override parent (if they are over 70% the same) */
}
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>
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