stig
stig

Reputation: 1220

Dynamic margin/padding with sass

Is it possible to simplify and make this more easily maintained with sass?

.padding-8 { padding: 8px !important; }
.padding-10 { padding: 10px !important; }

.padding-top-0 { padding-top: 0 !important; }
.padding-top-3 { padding-top: 3px !important; }

.padding-bottom-0 { padding-bottom: 0 !important; }
.padding-bottom-3 { padding-bottom: 3px !important; }
.padding-bottom-5 { padding-bottom: 5px !important; }

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

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

etc..

Is it also possible to write something like .padding-$dir-$value { padding-$dir: $value px !important; } so you can use a class with f.ex padding-left-13?

Upvotes: 1

Views: 3268

Answers (2)

Me Sa
Me Sa

Reputation: 1094

you can use this: (enhanced the above solution)

$paddingDirection:('right','left','top','bottom');
$paddingLength:(15,30,45,50);
// if you only wants to use "padding" without postfix
@each $len in $paddingLength {
  .padding-#{$len} { padding: #{$len}px;}
}

// if you want to use padding-left, padding-right etc.
@each $dir in $paddingDirection {
  @each $len in $paddingLength {
    .padding-#{$dir}-#{$len} { padding-#{$dir}: #{$len}px;}
  }
}

usage:
<div class="padding-15"></div>
<div class="padding-left-15 padding-top-15"></div>

Upvotes: 0

llobet
llobet

Reputation: 2790

  1. Make two maps with the properties you want to mix.
  2. For each combination create a placeholder class. I think it's appropiate if you don't want to create a full list of classes that maybe you won't use. This is the modular-friendly use.
  3. Extend the class in your element.

    $paddingDirection:('right','left','top','bottom');
    $paddingLength:(15,30,45,50);
    
    @each $dir in $paddingDirection{
      @each $len in $paddingLength{
        %padding-#{$dir}-#{$len}{ padding-#{$dir}: #{$len}px;}
      }
    }
    
    .any-class{
      @extend %padding-right-30;
    }
    
    /*output*/
    .any-class {
       padding-right: 30px;
    }
    

Original answer here

Upvotes: 2

Related Questions