69

I have this variable:

$gutter: 10;

I want to use it in a selector like so SCSS:

.grid+$gutter {
    background: red;
}

so the output becomes CSS:

.grid10 {
    background: red;
}

But this doesn't work. Is it possible?

4 Answers 4

104
$gutter: 10;

.grid#{$gutter} {
    background: red;
}

If used in a string for example in a url:

background: url('/ui/all/fonts/#{$filename}.woff')
1
  • I have a similar question also involving using variables in CSS Selectors. My question is long so I created a pastebin: pastebin.com/FkdNSaG7
    – jastako
    Dec 19, 2020 at 6:59
40

From the Sass Reference on "Interpolation":

You can also use SassScript variables in selectors and property names using #{} interpolation syntax:

$gutter: 10;

.grid#{$gutter} {
    background: red;
}

Furthermore, the @each directive is not needed to make interpolation work, and as your $gutter only contains one value, there's no need for a loop.

If you had multiple values to create rules for, you could then use a Sass list and @each:

$grid: 10, 40, 120, 240;

@each $i in $grid {
  .g#{$i}{
    width: #{$i}px;
  }
}

...to generate the following output:

.g10  { width: 10px; }
.g40  { width: 40px; }
.g120 { width: 120px; }
.g240 { width: 240px; }

Here are some more examples..

0
3

Here is the solution

$gutter: 10;

@each $i in $gutter {
  .g#{$i}{
     background: red;
  }
}
1
  • 1
    This only outputs .g10
    – Roel
    Jan 9, 2017 at 14:10
0

if it would be a vendor prefix, in my case the mixin did not compile. So I used this example

@mixin range-thumb()
  -webkit-appearance: none;
  border: 1px solid #000000;
  height: 36px;
  width: 16px;
  border-radius: 3px;
  background: #ffffff;
  cursor: pointer;
  margin-top: -14px; 
  box-shadow: 1px 1px 1px #000000, 0px 0px 1px #0d0d0d;

input[type=range]
  &::-webkit-slider-thumb
    @include range-thumb()
  &::-moz-range-thumb
    @include range-thumb()
  &::-ms-thumb
    @include range-thumb()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.