3

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Brilliant, thank you for your answer - just what I need!
You are very welcome. Thanks for your reply. Have a good time!
3

Try this one for better result

$spaceamounts: (5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 75, 100); // Adjust this to include the pixel amounts you need.
$sides: (top, bottom, left, right); // Leave this variable alone

@each $space in $spaceamounts {
  @each $side in $sides {
    .m#{str-slice($side, 0, 1)}-#{$space} {
      margin-#{$side}: #{$space}px !important;
    }
  }
}

Results

.mt-5 {
  margin-top: 5px !important;
}

.mb-5 {
  margin-bottom: 5px !important;
}

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

.mr-5 {
  margin-right: 5px !important;
}
...
...

1 Comment

That's great, thank you so much for your answer, unfortunately you were slightly slower than Nico, otherwise I would have give you the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.