Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically creating a list of css values in SCSS based on array

Tags:

css

sass

I'd like to do is create a list of margin css classes based on am array of numbers.

e.g. i'd like my css to look like this.

.ml-5 { margin-left: 5px; }

.ml-10 { margin-left: 10px; }

.ml-15 { margin-left: 15px; }

I want to do something like the following in my SCSS file to generate these for a set list of numbers

$list: 5, 10, 15, 20, 25, 30;

@each $n in $list {
    .ml-$n: margin-left:$n;
}

Anyone know if this can be done?

like image 821
user3284707 Avatar asked Mar 08 '26 02:03

user3284707


1 Answers

You were pretty close actually. You can use this syntax to generate the desired classes:

$list: 5, 10, 15, 20, 25, 30;

@each $n in $list {
    .ml-#{$n} { margin-left:$n; }
}

the #{$n} is called interpolation and is required to make your variables accessible in the way needed here.

like image 157
Nico O Avatar answered Mar 10 '26 16:03

Nico O



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!