Sim*_*Phy 4 css sass ampersand
我想使用以下模式选择父级。
我知道我可以在父选择器中写这个,但我想知道是否可以在子选择器中将父类的伪类作为子类的前缀。
JSX:
<div class="parent">
<div class="child" />
</div>
<div class="parent">
<div class="child" />
</div>
Run Code Online (Sandbox Code Playgroud)
社会保障:
.parent {
height: 100px;
.child {
// the goal is to write this so it produces the CSS output below, from
// within .child
&:first-child & {
height: 50px;
}
}
}
Run Code Online (Sandbox Code Playgroud)
CSS [输出]:
.parent:first-child .child {
height: 50px;
}
Run Code Online (Sandbox Code Playgroud)
所以看起来这真的很容易。哎呀。
您只需执行以下操作:
社会保障:
.child {
.parent:first-child & {
height: 50px;
}
}
Run Code Online (Sandbox Code Playgroud)
这可能看起来很傻,但对于我的情况,它实际上很有用。
小智 6
也许不是最有用的代码,但有效:
SASS
.parent {
$root: &;
height: 100px;
@at-root {
.child {
@at-root {
#{$root}:first-child #{&} {
height: 50px;
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出
.parent {
height: 100px;
}
.parent:first-child .child {
height: 50px;
}
Run Code Online (Sandbox Code Playgroud)