这是我第一次发现 & parent 选择器非常有用,这样我就不需要为了修改子元素而重新定义父级。
当然,使用 LESS 这实际上很容易,但我不得不问!
<div id="skrollr-body" class="nonav">
<div class="skrollable">
</div>
</div>
#skroller-body {
.skrollable {
margin-top:40px;
.nonav & {
// this parent selector lets me modify
// .skrollable without duplicating it
margin-top:0px;
}
}
}
.nonav &
的输出是.nonav #skroller-body .skrollable
我想知道我是否可以得到
#skroller-body.nonav .skrollable
而是以某种方式没有额外的 HTML 标记(包装器 div.nonav
)?目前我只会复制 parent
#skrollr-body {
margin-top:40px;
left:0;
width:100%;
.skrollable {
margin-top:40px;
position:fixed;
z-index:100;
.skrollable {
position:absolute;
.skrollable {
position:static;
}
}
}
&.nonav {
.skrollable {
margin-top:0px;
}
}
}
或节省冗余输出;
#skroller-body.nonav .scrollable { margin-top:0px; }
但这里的重点是易于维护和阅读的 CSS 代码。
最佳答案
The
&
operator represents the parent selectors of a nested rule and is most commonly used when applying a modifying class or pseudo-class to an existing selector
所以:
#skroller-body {
&.nonav {
.skrollable {
// stuff
}
}
}
}
关于减少 CSS : & reverse parent with multiple classes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13146694/