How to generate multiple values in four directions of padding and margin with less and sass?

Time:2022-5-14

When building the front-end framework some time ago, a small problem was recorded:

Previously, different values for padding and margin in the page will be set separately under the public style file. As shown in the figure below, both less and sass support function operation to optimize the code.

How to generate multiple values in four directions of padding and margin with less and sass?

Sass Code:

/*
 *Dynamically generate padding and margin values
 *$position shorthand setting of four positions
 *$type padding short for margin
 *Form 1 through 6 is the value of 1-6. The maximum distance of the set margin is 30. If necessary, others can be added
 *$Val: $I * 5 is the multiple of setting the distance step size to 5
 */ 
 $position:("t":"top", "b":"bottom", "l":"left", "r":"right");
 $type:("p":"padding", "m":"margin");
 @each $item in $type {
     @each $list in $position {
         @for $i from 1 through 6 {
             $val: $i * 5;
             .#{nth($item,1)}#{nth($list,1)}#{$val} {
                 #{nth($item,2)}-#{nth($list,2)}: #{$val}px;
             }
         }
     }
 }

Less margin setting

//Margin
@arr: 5, 10, 15, 20, 25, 30, 35, 40, 45, 50;

each(@arr, {
  @num:extract(@arr, @index);
  [email protected]{value} {
    margin-top:~"@{num}px";
  }
  [email protected]{value} {
    margin-right:~"@{num}px";
  }
  [email protected]{value} {
    margin-bottom:~"@{num}px";
  }
  [email protected]{value} {
    margin-left:~"@{num}px";
  }
  [email protected]{value} {
    padding-top:~"@{num}px";
  }
  [email protected]{value} {
    padding-right:~"@{num}px";
  }
  [email protected]{value} {
    padding-bottom:~"@{num}px";
  }
  [email protected]{value} {
    padding-left:~"@{num}px";
  }
});