如何在Less中的子类中对祖父项应用条件 [英] How to apply condition on grandparent from within the child class in Less

查看:679
本文介绍了如何在Less中的子类中对祖父项应用条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<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>

使用Less如何根据grandParent类应用子文本颜色

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;
  }
}


推荐答案

最可维护的代码是这样的我想:

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

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



<真正想要使用:not ):

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

请参阅更改选择器顺序以了解此类& / code>使用。

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]
虽然如果真的需要维护它,可以这样说:


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


  1. 避免使用太具体的选择器(因此对于这个例子,我认为 .grandParent .parent 实际上是冗余的)。

  2. 为了嵌套,不要嵌套。有时嵌套是好的,但有时它是非常丑陋(请参阅这个很好的简短答案只是几个原因,从不这样做)盲目)。

  3. DRY!= maintainable。通常为平面样式重复一个或两个类比编写a肿和混乱的类层次结构(通常对于这种情况,混合和/或选择器插值比平面嵌套更好)。例如。而不是让它更容易修改(通常这是在DRY太重的唯一原因)认为如果你可以写它,你永远不会希望它被修改的方式。

  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.

这篇关于如何在Less中的子类中对祖父项应用条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆