LoginSignup
6
6

More than 5 years have passed since last update.

ボックスの文字サイズと行間を反映した上下余白をremで返すmixin

Last updated at Posted at 2016-10-30

box-spacing.jpg

見出しやボタンなどで、こういうコーディング指示はよく来ます。

ボーダーが上下2px、文字が一行だったときのボックス高さは44px。
中のテキストは、文字サイズが16px、行間は150%(1.5)です。

すべての要素を反映して上と下の余白を割り出す必要がありますが、手計算が面倒だし、remを使いたいので、以下のようなmixinを使っています。

box-spacing.scss
// px高さと文字サイズから必要な余白を計算し、remで返す

@mixin box-spacing( $height: 30, $font-size: 16, $line-height: 1.35, $border-top: 0, $border-bottom: 0, $rem: 16 ) {
  padding-top: ( ( ( $height - ( $border-top + $border-bottom ) - ( $font-size * $line-height ) ) / 2 ) / $rem ) * 1rem;
  padding-bottom: ( ( ( $height - ( $border-top + $border-bottom ) - ( $font-size * $line-height ) ) / 2 ) / $rem ) * 1rem;
}

SaSS内ではこのように使います。文字サイズの基準値が16pxではない場合は最後の引数を足します。

box-spacing_call.scss
.example {
  @include box-spacing( 44, 16, 1.5, 3, 3 );
}

これの欠点は「上下に均等な余白がある要素にしか使えない」ことなのですが、その場合は上にも余白があることにしてざっとコンパイルし、結果のCSSをコピペしたりして使っています。

6
6
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
6
6