SCSS混合器,如何连接单位?(px、%、em)

5

我想定义类,如下所示:

.bg-1 {
   width: 1%
}
.bg-2 {
   width: 2%
}

我正在尝试使用以下方法:

@for $i from 1 through 100 {    
  .bg-#{$i} {
    width: #{$i};
  }
}

这至少可以编译,但会打印出以下内容。
    .bg-1 {
       width: 1;
    }
    .bg-2 {
       width: 2;
    }

问题在于,如果我添加以下内容:
width: #{$i}%;

我得到:

error sass/screen.scss (Line 294 of sass/modules/_classes.scss: Invalid CSS after "   $var: ": expected expression (e.g. 1px, bold), was "%;")

尝试使用 width: #{$i} + '%'; 或者 width: #{$i}'%'; - Andy Furniss
这将生成 .bg-95{width:95+"%"}.bg-95{width:95"%"}... - Toni Michel Caubet
@cimmanom 如果你的意思是我应该 $percent: 1% 然后 'width: #{$i}$percent;我在提问之前已经尝试过了... 结果是.bg-95{width:951%"}`。 - Toni Michel Caubet
2个回答

5
或者是更流行的这种方式。
@for $i from 1 through 100 {    
  .bg-#{$i} {
    width: round(percentage($i/100)); // Math function
    height: #{$i}px; // For px or em just concat
  }
}

3
尝试这个解决方案。它有效。
@for $i from 1 through 100 {    
   .bg-#{$i} {
     $percentage: unquote("%");
     width: #{$i}$percentage;
   }
}

或者这个:
 @for $i from 1 through 100 {    
  .bg-#{$i} {
    width: #{$i}unquote("%");
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接