Using CSS to avoid tagging element that are inside the element

Viewed 63

How do I avoid tagging css to the below code. I've tried a few things e.g. tried first:child but that didnt seem to work. I would just like the outer lis to be red not the second lis within the parent li

li {
  color: red;
}
<ul>
  <li>Tag this as red
    <ul>
      <li>
        Dont' tag this as color red
      </li>
    </ul>
  </li>
  <li>Tag this as red
    <ul>
      <li>
        Dont' tag this as color red
      </li>
    </ul>
  </li>
</ul>
```

3 Answers

you can use just classes to separate each one of them

.tagged-red {
  color: red;
}

.untagged-red {
  color: black;
}
<ul>
  <li class="tagged-red">Tag this as red
    <ul>
      <li class="untagged-red">
        Dont' tag this as color red
      </li>
    </ul>
  </li>
  <li class="tagged-red">Tag this as red
    <ul>
      <li class="untagged-red">
        Dont' tag this as color red
      </li>
    </ul>
  </li>
</ul>

Use direct child combinator > along with initial:

ul>li {
  color: red;
}

ul>li>ul>li {
  color: initial;
}
<ul>
  <li>Tag this as red
    <ul>
      <li>
        Dont' tag this as color red
      </li>
    </ul>
  </li>
  <li>Tag this as red
    <ul>
      <li>
        Dont' tag this as color red
      </li>
    </ul>
  </li>
</ul>

The reason you need to reset it on the inner lis is a) color is one of the inherited properties (any element will have the text color defined closest in its ancestor tree, unless it explicitly has a color set), and b) that ul>li will also match the inner lis.

The child combinator > is placed between two CSS selectors. It matches only those elements matched by the second selector that are the direct children of elements matched by the first. (for more information about child combinator you can read this.

But in your case, This doesn't work, because inner <li> inherits color from outer <li>, and both turn red.

.outer{
  color:red;
}
.inner{
  color:initial;
}
<ul>
    <li class="outer"> This shoud be red
      <ul>
        <li class="inner">
          This shoudn't be red
        </li>
      </ul>
    </li>
    <li class="outer">  This shoud be red
      <ul>
        <li class="inner">
          This shoudn't be red
        </li>
      </ul>
    </li>
  </ul>

For more read about inheritance in css, you can read this article

Related