How to apply condition on grandparent from within the child class in Less

我怕爱的太早我们不能终老 提交于 2019-12-12 02:52:07

问题


<div class="grandParent active"> /*active class added dynamically*/
   <div class="parent1">
    <div class="childOfParent1">  Some Text  </div>
   </div>
   <div class="parent2">
     <div class="childOfParent2">  Some Text  </div>
   </div>
</div>

Using Less how can i apply the child text color depending on grandParent class

.grandParent {
  .parent1 {
    .childOfParent1 {
      color : red;
      .grandParent:not(active) .parent1 .childOfParent1 {
        color : green;
      }
    }
  }
} 

The above is possible using the below code but i do not want to repeat the code

.grandParent {
  .parent1 {
    .childOfParent1 {
      color : red;
    }
  }
  &:not(active) .parent1 .childOfParent1 {
      color : green;
  }
}

回答1:


The most maintainable code would be something like this I guess:

.parent {
    .child {
        color: green;
        .grandParent.active & {color: red}
    }
}

Or less DRY (if you really want to get use of :not):

.parent {
    .child {
        .grandParent              & {color: red}
        .grandParent:not(.active) & {color: green}
    }
}

See Changing selector order for more details on such & usage.


Following the comments below here's another variant:

.grandParent {
    .parent {
        .child {
            color: green;
            .active& {color: red}
        }
    }
}

[Well, slightly offtopic] Though if really takes into getting it maintainable, there're a few remarks:

  1. Avoid too specific selectors (so for this example I think either .grandParent or .parent are redundant actually).
  2. Never nest for the sake of nesting. Sometimes nesting is good but sometimes it's extremely ugly (see this nice brief answer for just a few of many reasons for never doing it blindly).
  3. DRY != maintainable. Often repeating one or two classes for "flat" styles are much better than writing a bloated and cluttered class hierarchy (Usually for such cases mixins and/or selector interpolation works better than plain nesting). E.g. instead of making it more easy modifiable (usually this is the only reason for being too heavy on DRY) think if you could write it the way you'll never want it to be modified at all.


来源:https://stackoverflow.com/questions/26505932/how-to-apply-condition-on-grandparent-from-within-the-child-class-in-less

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!