首页 > 解决方案 > 如何使用 LESS 从深度嵌套的 HTML 元素中定位父 HTML 元素?

问题描述

是否可以在 LESS 文件中定位外部(“great-grand-”)“父”HTML 元素,其中元素可互换地div嵌套在元素内部?span

例如:

<div class="parent1 class1 class2">Parent shape
  <span class="parent2">
    <div class="parent3">      
      <div class="parent4 some-other-class">
         Some content.... 
      </div>
    </div> 

  </span>
</div>

我想要实现的是在嵌套最深的元素应用了这些类“ ”时,为div具有“”类的 FIRST 元素应用样式。.parent1 class1 class2div.parent4 some-other-class

重要笔记:

  1. 默认情况下,最深层嵌套div的元素只.parent4应用了类
  2. 样式应应用于应用了以下类的顶级父div元素parent1 class1 class2
  3. TOP-PARENTdiv元素的样式应该在且仅some-other-class当类被附加到嵌套最深的 DIV 时应用(即当它是 时<div class="parent4 some-other-class">

这是我现在的.less文件:


.parent1{
  &.class1.class2{
    div.parent.some-other-class & div.parent3 & span.parent2 {
      //css styling applied for `div.parent1.class1.class2`
    }
  }
}

...但它不工作。顺便说一句,所有选择器都必须.parent1在 LESS 文件中的类内 -> 这意味着 .less 文件必须是这样的:

.parent1{
   // ALL other selectors (e.g. `.parent2` , `.parent4.some-other-class` ) are inside of this block!
}

...而不是这样:

.parent1{
  /* styling */
}

.parent4.some-other-class{
  /* styling */
}

这是与此问题相关的最相似的问答,但它适用于存在单亲和单子元素的最微不足道的情况。

非常感谢任何帮助/建议。

标签: htmlcssless

解决方案


推荐阅读