1
0

More than 3 years have passed since last update.

scssでmargin-topとmargin-rightとセレクタを自動生成する。

Last updated at Posted at 2020-03-09

はじめに

ページやブロックごとに少しづつmarginが違うときに使いたいscssです。
生成されるcssは5px刻みです。
.mt-5.mt-200
.mr-5.mr-200

デザイナーからデザインをもらったけど、marginが統一されていない時がよくあります。
新たなclassとcssを追加するのは運用する上で最適解ではないように思います。

普段はBEMで書いているのでできるだけシングルクラスで書いていましたが、
marginとその他のプロパティはそれぞれで独立させた方いいのではないかと思いました。

動作環境

  • SCSS

コード

margin.scss

$breakpoint:768px;
//pcとspでmarginが変わるものに対応
@mixin pc {
  @media print, screen and (min-width: $breakpoint) {
    @content;
  }
}
@mixin sp {
  @media only screen and (max-width: ($breakpoint)) {
    @content;
  }
}

//5px-200pxまで5px刻み
@for $i from 1 through 40 {
  $i: $i * 5;
  .mt-#{$i} {
    margin-top: #{$i}px;
  }
  .mr-#{$i} {
    margin-right: #{$i}px;
  }
  @include pc{
    .pc-mt-#{$i} {
      margin-top: #{$i}px;
    }
    .pc-mr-#{$i} {
      margin-right: #{$i}px;
    }
  }
  @include sp{
    .sp-mt-#{$i} {
      margin-top: #{$i}px;
    }
    .sp-mr-#{$i} {
      margin-right: #{$i}px;
    }
  }
}

おわりに

こうすることで、要素に対するプロパティはその要素のデザインに関するものだけになり、
場所を移動させたり他のページにも表示させる際のmarginの違いに悩まなくなります。

しばらく運用してみて、問題があればアップデートできればと思います。
css設計も見直しが必要かもしれないですね。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0