Yujun Wu
Yujun Wu

Reputation: 3012

DRY Sass codes that only value changes

Using sass with rails. In the design, there is a pattern that the space shrink to half from desktop to mobile. Now it ends up like:

.my-page {
  .class-a {
    margin-top: 20px;
    margin-bottom: 20px;
  }
  .class-b {
    padding-top: 30px;
    padding-bottom: 30px; 
  }
}

@media(min-width: 768px) {
  .my-page {
    .class-a {
      margin-top: 40px;
      margin-bottom: 40px;
    }
    .class-b {
      padding-top: 60px;
      padding-bottom: 60px; 
    }
  }
}

Wondering is there a good way to DRY these? Don't wanna repeat writing same classes twice.

Upvotes: 0

Views: 58

Answers (2)

mgrim
mgrim

Reputation: 1302

A nice way to DRY up your sass is using mixins.

@mixin page-spaces($margin, $padding) {
  .my-page {
    .class-a {
      margin-top: $margin;
      margin-bottom: $margin;
    }
    .class-b {
      padding-top: $padding;
      padding-bottom: $padding; 
    }
  }
}

@include page-spaces(20px, 30px);

@media(min-width: 768px) {
  @include page-spaces(40px, 60px);
}

SASS Reference on Mixins

Edit: In order to clarify the intended use of mixins, here's an extended version with multiple arguments (even a default):

@mixin awesome-page-stuff($stylish-margin, $cute-padding, $some-left-margin, $ugly-background: red) {
  .my-page {
    background: $ugly-background;
    .class-a {
      margin-top: $stylish-margin;
      margin-bottom: $stylish-margin;
    }
    .class-b {
      padding-top: $cute-padding;
      padding-bottom: $cute-padding; 
      margin-left: $some-left-margin;
    }
  }
}

@include awesome-page-stuff(20px, 30px, 50px);

@media(min-width: 768px) {
  @include awesome-page-stuff(40px, 60px, 200px, green);
}

Upvotes: 2

Igor Ivancha
Igor Ivancha

Reputation: 3451

you can create variables, something like this:

$primary-margin: 20px;
$primary-padding: 30px;
.my-page {
  .class-a {
    margin-top: $primary-margin;
    margin-bottom: $primary-margin;
  }
  .class-b {
     padding-top: $primary-padding;
     padding-bottom: $primary-padding; 
  }
}

@media(min-width: 768px) {
  .my-page {
    .class-a {
      margin-top: $primary-margin*2;
      margin-bottom: $primary-margin*2;
    }
    .class-b {
      padding-top: $primary-padding*2;
      padding-bottom: $primary-padding*2; 
    }
  }
}

Upvotes: 0

Related Questions