父选择器少

时间:2015-04-24 09:32:09

标签: css less

通常以较少的方式引用父选择器:

.parent {
    .grand-pa & {
       /* this rules will apply to: .grand-pa .parent {....}
       background: grey;
    }
}

我尝试做的事情是类似的。示例代码HTML:

    <div class="panel panel-parent">
        <div class="panel-child">
            {{content}}
        </div>
    </div>

少代码:

.panel {
    .panel-child {
        // some rules
        &.panel-parent & {  //<=== IS IT POSSIBILE SOMETHING LIKE THIS??
            // .panel.panel-parent .panel-child{...}
        }
    }
}

我找到的唯一解决方案是重复.panel-child:

.panel {
        &.panel-parent .panel-child {  //<=== Workaround
            // .panel.panel-parent .panel-child{...}
        }        
        .panel-child {
        // some rules
        }
    }
}

1 个答案:

答案 0 :(得分:4)

同一元素的类的顺序实际上并不重要,即.panel.panel-parent等于.panel-parent.panel(两者都匹配<div class="panel panel-parent">),因此你可以得到你需要的东西:

.panel {
    .panel-child {
        a: a;
        .panel-parent& {
            b: b;
        }
    }
}

代替。