user3386779 user3386779 - 6 months ago 29
CSS Question

Target list items in primary ul but not nested ul

I need to add css styles to parent list.

I have one parent

ul
and children. I want to apply color to fruits, vegetables and flowers but not Apple, Banana, Orange.

I want to do this using a CSS selector.



ul:root>li {
color: red;
}

<ul>
<li>Fruits
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Orange</li>
</ul>
</li>

<li>Vegetables</li>
<li>Flowers</li>
</ul>




Answer

You could simply add a class to the parent ul and then use the direct descendant selector to target only those li items.

This is definitely going to change the colors for Apple or Orange but you can then reset the color on the sub ul items.

Here's your updated demo.

.parent-list > li {
  color: red;
}
.parent-list > li ul {
  color: initial;
}
<ul class="parent-list">
  <li>Fruits
    <ul>
      <li>Apple</li>
      <li>Banana</li>
      <li>Orange</li>
    </ul>
  </li>

  <li>Vegetables</li>
  <li>Flowers</li>
</ul>