我目前正在使用 sass 来帮助构建我的 CSS。下面给出一个简单的例子。
.container {
.list {
.selected {
background-image : url('highlighted.png');
}
}
}
不过,我也在使用 modernizr ( http://modernizr.com/docs/ ) 并希望尽可能使用 CSS3。在此示例中,我想测试 border-radius
的可用性,并使用 border-radius
而不是背景图像。因此,我需要检查 html
元素上是否存在 borderradius
类。是否有可能通过某种背后的观察来实现这一目标?或者我是否必须使用 .borderradius
类再次重复代码,最终结果如下:
.container {
.list {
.selected {
background-image : url('highlighted.png');
}
}
}
.borderradius .container {
.list {
.selected {
background : yellow;
border-radius : 10px;
}
}
}
在我看来,这在大型元素中看起来很困惑且难以维护。有没有人有更优雅的方法来实现这一目标?
最佳答案
您可以使用与号 (&) 来引用父选择器,如下所示:
.container {
.list {
.selected {
background-image : url('highlighted.png');
.borderradius & {
background : yellow;
border-radius : 10px;
}
}
}
}
将编译为:
.container .list .selected {
background-image : url('highlighted.png');
}
.borderradius .container .list .selected {
background : yellow;
border-radius : 10px;
}
查看 this article , 或 this one要更深入地解释它的用处:
...you can place a trailing ampersand (&) character at the end of your selector declaration in place of the repeating selector, and sit back and enjoy the awesomeness of Sass
关于CSS 'lookbehind' 使用 sass/less,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14706595/