Search code examples
cssless

How to apply class style on everything but a specific class and its children?( Nested Theme )


html

<ul class="style-b">
  <li>Item One</li>
  <li>Item Two
    <ul>
      <li>2.1</li>
      <li>2.2</li>
    </ul>
  </li>
  <li>Item Three
    <ul class="style-a">
      <li>3.1
        <ul>
          <li>3.1.1</li>
          <li>3.1.2</li>
          <li>3.1.3
            <ul class="style-b">
              <li>3.1.3.1</li>
              <li>3.1.3.2</li>
            </ul>
          </li>
        </ul>
      </li>
      <li>3.2</li>
    </ul>
  </li>
</ul>

less

.style-b {
  li {
    color: rebeccapurple;
  }
}
.style-a {
  li {
    color: black;
  }
}

result img result-img The .style-a has higher priority so that the nested .style-b doesn't work. I simplify the css style to one-level nesting li style,actually it has multiple nested class in my project.

I have tried to use :not() to exclude another,but seems compound selectors inside is prohibited.

.style-b *:not(.style-a *) {
  li {
    color: rebeccapurple;
  }
}
.style-a *:not(.style-b *) {
  li {
    color: black;
  }
}

I am now adding another class .important to improve the priority,and add important in nested one. But it can only support two-level nesting,and is really foolish.

._styleA() {
  li {
    color: black;
  }
}
._styleB() {
  li {
    color: rebeccapurple;
  }
}
.style-a {
  ._styleA()
}
.style-a.important {
  ._styleA()
}
.style-b {
  ._styleB()
}
.style-b.important {
  ._styleB()
}

Solution

  • I finally figure it out that my question is how to realize nested theme. I found the react UI frame ant design's nested theme satisfied my needs. And i will realize a same one myself.

    see css-var-plan of ant design