Say you need to use a certain selector in multiple places in your code. It’s not tremendously common, to be sure, but stuff happens. Repeated code is typically an opportunity for abstraction. Abstracting values in Sass is easy, but selectors is slightly trickier.
One way to do it is to create your selector as a variable. Here’s an example that is a comma separated list of selectors:
$selectors: "
.module,
body.alternate .module
";
Then to use that, you have to interpolate the variable, like this:
#{$selectors} {
background: red;
}
That works with nesting too:
.nested {
#{$selectors} {
background: red;
}
}
Prefixing
A variable can also be only a part of a selector, like a prefix.
$prefix: css-tricks-;
.#{$prefix}button {
padding: 0.5rem;
}
You could use nesting to do prefixing as well:
.#{$prefix} {
&module {
padding: 1rem;
}
&header {
font-size: 110%;
}
&footer {
font-size: 90%;
}
}
Selectors in a Map
Perhaps your abstraction lends itself to a key/value pair situation. That’s a map in Sass.
$selectorMap: (
selectorsFoo: ".module",
selectorsBar: ".moodule-2"
);
You can use them individually like:
#{map-get($selectorMap, selectorsFoo)} {
padding: 1rem;
}
Or loop through them:
@each $selectorName, $actualSelector in $selectorMap {
#{$actualSelector} {
padding: 1rem;
}
}
Examples
See the Pen Sass Variables for Selectors by Chris Coyier (@chriscoyier) on CodePen.
You can also prefix like this:
http://codepen.io/RamonDreise/pen/XpWjVV
Nice. You can use & to reference a parent and $x to assign something as a variable.
This is quite useful when working with BEM.
I like that prefixing method, but I do it like this
.prefix {
&–stuff
}
That way if I have a class like .prefix-method, it will come out .prefix-method–stuff
A little function and mixin to add some flexibility
See the Pen SCSS selector mixin by jakob-e (@jakob-e) on CodePen.
A little function and mixin to add some flexibility
http://codepen.io/jakob-e/pen/ggOmjO/
cool, pretty useful for mixins. Just today I needed to have an optional sub-selector as a parameter so I can target styles for the default selector in the mixin, or some other children element, like this:
Be careful as sometimes this does not result in what you expect. Things like
div > #{$my-selectors}
will not expand to what you’d like it to expand.