Prevent CSS inheritance to children of the selected element

7.5k views Asked by At

I have a menu consisting of nested ULs and LIs, eg:

.wrapper > ul:first-child > li:last-child {
  color: red;
}
<div class="wrapper">
  <ul>
    <li>Lorem</li>
    <li>Ipsum</li>
    <li>Dolar</li>
    <li>Style me!
      <ul>
        <li>Lorem</li>
        <li>Don't style me!</li>
      </ul>
    </li>
  </ul>
</div>

I want to add a style to the last <li> of the first <ul>, but not have it's children (the nested <ul>) inherit it.

I have tried:

.wrapper > ul:first-child > li:last-child {/*styles*/}

but this still styles the last element.

Would anyone know how I can target just that 1 element (with just CSS)?

1

There are 1 answers

0
Oriol On BEST ANSWER

Some CSS properties are inherited and you can't prevent that.

Inheritance propagates property values from parent elements to their children.

Some properties are inherited properties, as defined in their property definition table. This means that, unless the cascade results in a value, the value will be determined by inheritance.

However, you can override that by selecting the children and restoring the desired value.

.wrapper > ul:first-child > li:last-child {
  color: red;
}
.wrapper > ul:first-child > li:last-child > * {
  color: initial;
}
<div class="wrapper">
  <ul>
    <li>Lorem</li>
    <li>Ipsum</li>
    <li>Dolar</li>
    <li>Style me!
      <ul>
        <li>Lorem</li>
        <li>Don't style me!</li>
      </ul>
    </li>
  </ul>
</div>