user3386779
user3386779

Reputation: 7185

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>

Upvotes: 2

Views: 1983

Answers (4)

Michael Benjamin
Michael Benjamin

Reputation: 371719

ul > li {                /* select list items that are children of a ul */
  color: red;
}

ul ul li {               /* select list items that are descendants of a ul, itself... */
  color: black;          /* ...a descendant of another ul */
}
<ul>
  <li>Fruits
    <ul>
      <li>Apple</li>
      <li>Banana</li>
      <li>Orange</li>
    </ul>
  </li>
  <li>Vegetables</li>
  <li>Flowers</li>
</ul>

Upvotes: 1

SMS
SMS

Reputation: 84

<style>
ul  li {
  color: red;
}

ul ul li {
  color: black;
}
</ul>

</style>


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

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

Upvotes: -2

Mani
Mani

Reputation: 2655

Use like this...

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

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

<style>
ul li{
  color: red;
}
ul li li{
  color: black;
}
</style>

Upvotes: 1

Praveen Puglia
Praveen Puglia

Reputation: 5631

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>

Upvotes: 2

Related Questions