Heisenberg
Heisenberg

Reputation: 67

CSS Child element vs descendant selector implementation issue

I am trying to learn CSS and came across the concept of child selector and descendant selector. To try this out I implemented the following HTML code and linked with the given CSS code.

ol>li {
  color: blueviolet;
}
<ol>
  <li>first main list item</li>
  <li>second main list item</li>
  <li>
    <ul>
      <li>first sub-list item</li>
      <li>second sub-list item</li>
    </ul>
  </li>
</ol>

My expectation was only the main list items to become blueviolet as this has been defined as a child selector. I thought the child selector will only select direct child elements and ignore the second level child elements. But instead, all sub-child and main-child elements became blue violet. Is my understanding wrong about these two selector types?

Upvotes: 2

Views: 80

Answers (3)

tacoshy
tacoshy

Reputation: 13012

As said before it selects li with all it child elements as text-color is inherited by default. To prevent a 2nd level list to inherit the text-color by default you have to reset it by using li > * { color: initial }. This will reset the text-color to the default color while no inheriting the color from the parent li element.

ol > li {
  color: blueviolet;
}

li > * {
  color: initial;
}
<ol>
  <li>first main list item</li>
  <li>second main list item</li>
  <li>
    <ul>
      <li>first sub-list item</li>
      <li>second sub-list item</li>
    </ul>
  </li>
</ol>

Upvotes: 0

Yupma
Yupma

Reputation: 2546

As you have putted ul inside child li tag of ol so whole are in color: blueviolet; . You have to put ul tag outside li tag or use a different approach for selector . Refer to below snippet for some ways .

ol>li {
  color: blueviolet;
}

.differ li>ul {
  color: red;
}
<h1>How code is running</h1>
<ol>
  <li>first main list item</li>
  <li>second main list item</li>
  <li>
    <ul>
      <li>first sub-list item</li>
      <li>second sub-list item</li>
    </ul>
  </li>
</ol>

<h1>Solution Way 1</h1>
<ol>
  <li>first main list item</li>
  <li>second main list item</li>
  <ul>
    <li>first sub-list item</li>
    <li>second sub-list item</li>
  </ul>
</ol>

<h1>Solution Way 2</h1>
<ol class="differ">
  <li>first main list item</li>
  <li>second main list item</li>
  <li>
    <ul>
      <li>first sub-list item</li>
      <li>second sub-list item</li>
    </ul>
  </li>
</ol>

Upvotes: 0

Ankit Sanghvi
Ankit Sanghvi

Reputation: 527

Yes. All <li> tags in your 1st list element are direct children of your <ol> so they all will have a blueviolet background when you use the ol > li CSS selector

What you're trying to achieve can be achieved by overriding this style with ol > li > ul > li selector to get different styles for these nested <li> elements

Upvotes: 2

Related Questions