2

Previously I used to create my helper CSS to aid rapid development. The contents of helper CSS were like:

.margin-10{
  margin:10px!important;
}
.....

and in HTML I could use <div class="margin-10"></div>

But then found SASS and it's amazing. It really helped me developing applications fast especially its mixin feature. But I have a problem. Here is a scenario.

SCSS Mixin is:

@mixin border-radius($radius) {
-webkit-border-radius: $radius;
 -moz-border-radius: $radius;
  -ms-border-radius: $radius;
      border-radius: $radius;
 }

 .box {
   @include border-radius(10px);
 }

in HTML I can use <div class="box"></div>

Is there any possibility to create dynamic classes? For example if I use <div class="margin-left-10"></div> it automatically creates margin left class using mixin. If I use <div class="padding-top-100"></div> padding-top-100 class is automatically created and manipulated using SASS mixin

2

1 Answer 1

3

Here a mixin that could help you :

@mixin createMargin($min, $max)
  @for $i from $min to $max+1
    .margin-#{$i}
      margin : 1px * $i !important

    .margin-top-#{$i}
       margin-top: 1px * $i !important

    .margin-left-#{$i}
       margin-left : 1px * $i !important

    .margin-right-#{$i}
       margin-right: 1px * $i !important

    .margin-bottom-#{$i}
      margin-bottom: 1px * $i !important

@include createMargin(0, 100) // Choose your min and max value

So you will just have to use <div class="XXX margin-top-40"></div> to have a 40px margin top on your div

2
  • But this would generate all margin classes from 0-100, right? What about compilation? Will only those classes be compiled which I used or it will compile margin classes ranging 0 to 100. Sep 25, 2017 at 15:26
  • Yes the problem is that this would generate all margin classes from 0 - 100 :/ Sep 25, 2017 at 15:31

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.