我在Sass中嵌套时遇到了问题。假设我有以下HTML:
<p href="#" class="item">Text</p>
<p href="#" class="item">Text</p>
<a href="#" class="item">Link</a>
当我尝试在下面的代码中嵌套我的样式时,我得到了一个编译错误:
.item {
color: black;
a& {
color:blue;
}
}
当类型选择器是同一元素的一部分时,如何在父选择器之前引用类型选择器?
发布于 2014-09-03 23:27:07
As Kumar points out,自从Sass 3.3.0.rc.1 (Maptastic Maple)
以来,这已经成为可能。
@ at -root指令导致在文档的根位置发出一个或多个规则,而不是嵌套在其父选择器的下面。
我们可以将@at-root
directive和interpolation #{}
结合起来,以达到预期的结果。
SASS
.item {
color: black;
@at-root {
a#{&} {
color:blue;
}
}
}
// Can also be written like this.
.item {
color: black;
@at-root a#{&} {
color:blue;
}
}
输出CSS
.item {
color: black;
}
a.item {
color: blue;
}
发布于 2015-02-06 01:30:12
如果您想在链上扩展最近的选择器,那么 @at-root
**-only方法不会解决这个问题。**例如:
#id > .element {
@at-root div#{&} {
color: blue;
}
}
将编译为:
div#id > .element {
color: blue;
}
如果需要将标签连接到.element
#id
**?**而不是,该怎么办
在Sass中有一个名为selector-unify()
的函数可以解决这个问题。在@at-root
中使用这一点,可以将.element
作为目标。
#id > .element {
@at-root #{selector-unify(&, div)} {
color: blue;
}
}
将编译为:
#id > div.element {
color: blue;
}
发布于 2013-06-24 05:45:17
对于初学者来说,(在写这个答案的时候)没有使用选择器和的sass语法。如果你要做这样的事情,你需要在选择符和和号之间留一个空格。例如:
.item {
.helper & {
}
}
// compiles to:
.helper .item {
}
使用&符号的另一种方式可能是您正在(错误地)寻找的:
.item {
&.helper {
}
}
// compiles to:
.item.helper {
}
这允许您使用其他类、ID、伪选择器等来扩展选择器。不幸的是,从理论上讲,这会编译成像.itema这样的东西,显然不起作用。
您可能只想重新考虑一下如何编写CSS。有没有可以使用的父元素?
<div class="item">
<p>text</p>
<p>text</p>
<a href="#">a link</a>
</div>
这样,你就可以很容易地用下面的方式写出你的SASS:
.item {
p {
// paragraph styles here
}
a {
// anchor styles here
}
}
(附注:你应该看看你的html。您将混合使用单引号和双引号,并将href属性放在p标记上。)
https://stackoverflow.com/questions/17268051
复制相似问题