Can I use variables for selectors?

28,673

Solution 1

$gutter: 10;

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

If used in a string for example in a url:

background: url('/ui/all/fonts/#{$filename}.woff')

Solution 2

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..

Solution 3

Here is the solution

$gutter: 10;

@each $i in $gutter {
  .g#{$i}{
     background: red;
  }
}
Share:
28,673
Johansrk
Author by

Johansrk

Updated on July 05, 2022

Comments

  • Johansrk
    Johansrk almost 2 years

    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?

  • Roel
    Roel over 7 years
    This only outputs .g10
  • Admin
    Admin over 3 years
    I have a similar question also involving using variables in CSS Selectors. My question is long so I created a pastebin: pastebin.com/FkdNSaG7