Use a Sass Variable for a Selector

0
0

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;
  }
}
  • You must to post comments
Showing 1 result
Your Answer

Please first to submit.