Home > Blockchain >  Using CSS to avoid tagging element that are inside the element
Using CSS to avoid tagging element that are inside the element

Time:12-06

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>
```
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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.

CodePudding user response:

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>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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

CodePudding user response:

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>
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related