¿Puedo usar variables para selectores?


Tengo esta variable:

$gutter: 10;

Quiero usarlo en un selector como so SCSS:

.grid+$gutter {
    background: red;
}

Así que la salida se convierte en CSS:

.grid10 {
    background: red;
}

Pero esto no funciona. Es posible?

Author: BoltClock, 2012-10-05

4 answers

$gutter: 10;

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

Si se usa en una cadena, por ejemplo, en una url:

background: url('/ui/all/fonts/#{$filename}.woff')
 97
Author: glortho,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-27 17:36:16

De la Referencia Sass sobre "Interpolación":

También puede usar variables SassScript en selectores y nombres de propiedades usando # {} sintaxis de interpolación:

$gutter: 10;

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

Además, el @each la directiva no es necesaria para hacer que la interpolación funcione, y como su $gutter solo contiene un valor, no hay necesidad de un bucle.

Si tuviera varios valores para crear reglas, podría usar una lista Sass y @each:

$grid: 10, 40, 120, 240;

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

Generate para generar la siguiente salida:

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

Aquí hay algunos ejemplos más..

 38
Author: fk_,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-13 21:33:21

Aquí está la solución

$gutter: 10;

@each $i in $gutter {
  .g#{$i}{
     background: red;
  }
}
 2
Author: Johansrk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-05 10:05:38

Si fuera un prefijo de proveedor, en mi caso el mixin no compiló. Así que usé este ejemplo

@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()
 0
Author: Artemee Senin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-13 08:29:43