Sass:来自变量的多个类选择器
我想用这样的类创建一个变量
$multi: foo, bar, baz
我想创建一个像这样的组合选择器:
.foo, .bar, .baz {}
我使用缩进语法(不知道这是否重要)。我想要从变量生成组合选择器的原因是:我需要根据那里定义的类数量进行计算。请不要给出类似(使用扩展!)的建议,因为这将需要我再上一堂课。我需要能够接近或完全接近常规组合选择器输出。
I want to create a variable with classes like so
$multi: foo, bar, baz
And I want to created a combined selector like so:
.foo, .bar, .baz {}
I am used the indented syntax (don't know if that would matter). The reason I want the combined selector generated from the variable: I need to do calculations based on how many classes are defined there. Please don't give a suggestion like (use extends!) because that will require me to make another class. I need to be able to get close or exactly to the regular combined selector output.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我和OP有同样的问题,这是我找到的第一个搜索结果,所以现在我已经弄清楚了,我将发布我的解决方案,即使这个问题已经有1.5年的历史了。
这是我发现的:为了使用变量作为选择器,您可以使用 SASS 插值,它与逗号分隔的字符串完美配合。但是,如果您希望保存选择器的变量是一个
list
(以便您可以在其上使用列表函数,例如length($multi)
),则插值将生成一个格式错误的选择器。因此,简单的解决方案是首先将变量定义为列表,然后当您需要将其用作选择器时,将该列表转换为逗号分隔的字符串:
您可能希望将列表抽象为逗号分隔的-将字符串功能转换为函数(注意:SASS 的
join
函数不会执行此操作;它将两个列表连接到一个新列表中)。这是一种可能的实现:此时原始代码可以简洁为:
I had the same issue as the OP, and this was the first search result I found, so now that I’ve figured it out, I’ll post my solution, even though the question is 1.5 years old.
Here’s what I found out: in order to use a variable as a selector, you use SASS interpolation, which works perfectly with comma-separated strings. However, if you want the variable that holds your selectors to be a
list
(so that you can use list functions on it, e.g.length($multi)
), the interpolation will generate a malformed selector.So, the simple solution is to first define your variable as a list, then when you need to use it as a selector, convert that list into a comma-separated string:
You may want to abstract the list-to-comma-separated-string functionality into a function (note: SASS’s
join
function doesn’t do this; it joins two lists into a new one). Here’s one possible implementation:At which point the original code can be as concise as:
(之前答案中的代码)很酷的功能!有用的。我只是想添加一些SCSS语法,给人们一个使用它的机会:
此时原始代码可以简洁为:
(code from previous answer) Cool function! Usefull. I just wanted to add some SCSS syntax, to give an opportunity to people to use it:
At which point the original code can be as concise as:
Compass 提供了一个内置的 sprite mixin,可以实现此目的。 如果您不这样做想要使用 Compass 的全部内容,您可以查看他们的源代码以了解他们是如何做到这一点的。
Compass offers a built-in sprite mixin that does just this. If you don't want to use all of Compass, you could look into their source to see how they are doing it.