14
18

More than 5 years have passed since last update.

marginの上下・左右だけを一行で指定するMixin

Posted at

CSSのショートハンド仕様の疑問点

CSSを使ったレイアウトにはmargin/padding/borderなどボックスモデルに関するプロパティが欠かせませんが、標準で用意されている短縮記法(ショートハンド)では「上下だけ」や「左右だけ」を簡潔に指定する方法がありません。

example01.css
.example01 {
  margin: 10px;                /* 上下左右 */
  margin: 10px 20px;           /* 上下 左右 */
  margin: 10px 20px 30px;      /* 上 左右 下 */
  margin: 10px 20px 30px 40px; /* 上 右 下 左 */
}

(参考: ショートハンドプロパティ - CSS | MDN

これらのショートハンドは4辺のプロパティを一度に指定するため、必要以上に"0"の記述が増えたり、レスポンシブデザインのサイトでは重複指定が発生しやすい点が個人的に気になっていました。

example02_with_shorthand.css
.example02 {
  margin: 10px 0; /* 左右に無駄な"0"の指定 */
}

@media (min-width: 768px) {
  .example02 {
    margin: 10px 20px; /* 上下の値が上書きされるため重複が発生 */
  }
}
example02_without_shorthand.scss
.example02 {
  margin: {
    top: 10px;
    bottom: 10px; // 値が上下で分かれるのが不便
  }
}

@media (min-width: 768px) {
  .example02 {
    $spacing: 20px; // 変数化すると行数が増える
    margin: {
      left: $spacing;
      right: $spacing;
    }
  }
}

SassのMixinを使った試案

Sass(SCSS)を使うと任意のプロパティを組み合わせてMixin化できるため、「上下だけ」や「左右だけ」のmarginをピンポイントで指定するためのMixinを作ってみました。

example03.scss
@mixin margin-row($top: 0, $bottom: null) {
  margin: {
    top: $top;
    bottom: if($bottom != null, $bottom, $top);
  }
}

@mixin margin-column($left: 0, $right: null) {
  margin: {
    left: $left;
    right: if($right != null, $right, $left);
  }
}

.example03 {
  @include margin-row(10px); /* 無駄な"0"の指定が必要ない */
}

@media (min-width: 640px) {
  .example03 {
    @include margin-column(20px); /* 上下の値は上書きされない */
  }
}

@media (min-width: 1024px) {
  .example03 header {
    @include margin-row(30px, 40px); /* 上下別の値も一度に指定可能 */
  }
}

同じパターンでpadding/borderなど任意のプロパティの組み合わせをMixin化することもできます。

example03.scss
@mixin padding-row($top: 0, $bottom: null) {
  padding: {
    top: $top;
    bottom: if($bottom != null, $bottom, $top);
  }
}

@mixin padding-column($left: 0, $right: null) {
  padding: {
    left: $left;
    right: if($right != null, $right, $left);
  }
}

@mixin border-row($top: none, $bottom: null) {
  border: {
    top: $top;
    bottom: if($bottom != null, $bottom, $top);
  }
}

@mixin border-column($left: none, $right: null) {
  border: {
    left: $left;
    right: if($right != null, $right, $left);
  }
}
14
18
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
14
18