Html 如何在不到一年的时间里从儿童班中对祖父母施加条件

Html 如何在不到一年的时间里从儿童班中对祖父母施加条件,html,css,less,Html,Css,Less,上面的代码可以使用下面的代码,但我不想重复代码 .grandParent { .parent1 { .childOfParent1 { color : red; .grandParent:not(active) .parent1 .childOfParent1 { color : green; } } } } 我想最容易维护的代码应该是这样的: .grandParent { .parent1 { .chi

上面的代码可以使用下面的代码,但我不想重复代码

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

我想最容易维护的代码应该是这样的:

.grandParent {
  .parent1 {
    .childOfParent1 {
      color : red;
    }
  }
  &:not(active) .parent1 .childOfParent1 {
      color : green;
  }
}
或干燥程度较低(如果您确实想使用
:而不是
):

有关此类
用法的更多详细信息,请参阅


下面是另一个变体:

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

[嗯,有点离题] 虽然如果真的考虑到它的可维护性,有几点意见:

  • 避免使用太特定的选择器(因此在本例中,我认为
    .grandParent
    .parent
    实际上是多余的)
  • 永远不要为了筑巢而筑巢。有时筑巢是好的,但有时它是非常丑陋的(请参阅不盲目筑巢的许多原因中的一些)
  • 干的!=可维护的。通常,为“扁平”样式重复一个或两个类比编写臃肿杂乱的类层次结构要好得多(通常在这种情况下,混合和/或选择器插值比普通嵌套更有效)。例如,与其让它更容易修改(通常这是干得太重的唯一原因),不如考虑一下你是否可以用你根本不希望修改的方式来写

  • 您好,谢谢您的回答,但我的.parent1选择器随附在.祖父母选择器中。仅当.parent1选择器位于.祖父母选择器之外时,上述解决方案才有效。有什么方法可以从.祖父母选择器中对.祖父母应用条件吗?@seenimurugan:No mate,因为在末尾添加了
    &
    ,所以编译的CSS选择器类似于
    。祖父母:不(.active).parent1.childOfParent1
    。因此,结构实际上是相同的。只是将选择器嵌套在Less中的顺序进行了修改,以满足需要。是一个示例,供您使用答案中的代码。您好Harry,非常感谢您的时间,但是正如我前面所说的.parent1位于.祖父母中时,编译的输出是
    .grandParent.grandParent.parent1.childOfParent1{
    颜色:{ff0000;
    祖父母:不(.active).grandParent.parent1.parentofparent1{
    颜色:#008000;
    }
    。因此“some Text”不会像我预期的那样着色。使用这种方法,
    .parent1
    不应该位于实际较少文件中的
    .grandParent
    内。嵌套应以
    .parent1
    开始。但是,如果出于某种原因,您不赞成这种方法,那么您可能必须尝试类似的方法,但这在某种程度上也是重复编码。
    .parent {
        .child {
            color: green;
            .grandParent.active & {color: red}
        }
    }
    
    .parent {
        .child {
            .grandParent              & {color: red}
            .grandParent:not(.active) & {color: green}
        }
    }
    
    .grandParent {
        .parent {
            .child {
                color: green;
                .active& {color: red}
            }
        }
    }