Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SCSS mixin, how to concatenate units? (px,%,em) [duplicate]

I want to define classes like

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

And I'm trying with this:

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

This at least compiles, but prints out

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

the problem is that If I add:

width: #{$i}%;

I got:

error sass/screen.scss (Line 294 of sass/modules/_classes.scss: Invalid CSS after "   $var: ": expected expression (e.g. 1px, bold), was "%;")
like image 207
Toni Michel Caubet Avatar asked Oct 08 '15 08:10

Toni Michel Caubet


People also ask

How do I concatenate in SCSS?

The single Sass string operator is concatenation. Strings can be concatenated (linked together) using the + operator. If you mix quoted and unquoted strings when concatenating, the result will be whichever is on the left side of the operator.

What is the difference between mixin and extend in sass?

@mixin is used to group css code that has to be reused a no of times. Whereas the @extend is used in SASS to inherit(share) the properties from another css selector. @extend is most useful when the elements are almost same or identical.

What is the use of mixin in SCSS?

Sass Mixins The @mixin directive lets you create CSS code that is to be reused throughout the website. The @include directive is created to let you use (include) the mixin.

Can I use mixin in CSS?

CSS mixins​Any CSS stylesheet, class or element that is defined in a Stylable CSS file can be used as a mixin source. You can use either a local class or element, or import the mixin from a different stylesheet. In the following example, a locally defined class is used as a mixin in the same stylesheet.


2 Answers

Or something like this, which is more popular.

@for $i from 1 through 100 {    
  .bg-#{$i} {
    width: round(percentage($i/100)); // Math function
    height: #{$i}px; // For px or em just concat
  }
}
like image 53
sperovic Avatar answered Oct 07 '22 15:10

sperovic


Try this solution. It works.

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

Or this:

 @for $i from 1 through 100 {    
  .bg-#{$i} {
    width: #{$i}unquote("%");
  }
}
like image 44
marisaroque Avatar answered Oct 07 '22 15:10

marisaroque