我可以在 SASS 中使用&符号来引用父类的特定标签吗? [英] Can I use the ampersand in SASS to reference specific tags with the parent class?
问题描述
我有一个 semantic
类,我将它应用于许多不同的元素.根据类应用于哪个 html 标签,我希望它应用不同的样式.这就是我尝试这样做的方式:
I have a class semantic
which I apply to many different elements. Depending on which html tag the class is applied to, I would like it to apply a different style. This is how I tried to do it:
.semantic {
&ul {
padding: 0;
margin: 0;
}
&p {
margin: 0;
}
}
这不起作用.我当然可以这样写,但不会很干":
This doesn't work. Of course I could write it like this, but it wouldn't be very "DRY":
.semantic ul {
padding: 0;
margin: 0;
}
.semantic p {
margin: 0;
}
这可能吗?
为了澄清起见,以下是我的 HTML 外观示例:
For clarification, here is an example of what my HTML looks like:
<ul class='semantic'>
<li>An Item</li>
</ul>
<p class='semantic'>This text is semantically a paragraph, but should not be displayed as such</p>
推荐答案
理论上你想要的是这样的:
What you're wanting for would in theory look like this:
.semantic {
ul& {
padding: 0;
margin: 0;
}
p& {
margin: 0;
}
}
这是不可能的,因为 &
必须是第一个.你只需要处理它不是 DRY 的事实并用手写出来:
This is not possible because the &
must be first. You're just going to have to deal with the fact that it isn't DRY and write it out by hand:
ul.semantic {
padding: 0;
margin: 0;
}
p.semantic {
margin: 0;
}
从 Sass 3.3 或 3.4 开始,可以使用以下语法:
As of Sass 3.3 or 3.4, it is possible using this syntax:
.semantic {
ul#{&} {
padding: 0;
margin: 0;
}
p#{&} {
margin: 0;
}
}
这篇关于我可以在 SASS 中使用&符号来引用父类的特定标签吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!