LoginSignup
6
3

More than 5 years have passed since last update.

テキスト要素の先頭行だけline-heightを取り除き、上ぴったりに揃えるスタイルシートのテクニック

Last updated at Posted at 2018-10-11

考え方

1.テキスト要素の全高(文字の高さ+上スペース+下スペース)は、line-heightにfont-sizeを掛けたものに等しくなります。
2.文字の高さはfont-sizeと等しい(近似値)と仮定します

2018082003.png
グリーン: font-size、オレンジ: font-sizeとline-height、■ブラック: 上スペース

先頭行だけを上に揃えるには、テキストのブロックからline-heightで加えられた上部のスペースだけを取り除けば実現できます。

SASS

@mixin lhCrop($line-height) {
  &::before {
    content: '';
    display: block;
    height: 0;
    width: 0;
    margin-top: calc((1 - #{$line-height}) * 0.5em);
  }
}

適用するテキスト要素に上記を含め、Mixinの引数としてline-heightの値を渡します。

.text-to-crop {
  @include lhCrop(1.2); //line-height: 1.2
}

demo

このルールは、使用するフォントによって異なります。例えばRobotoの文字の高さだと、font-sizeの75%になります。使用するフォントに合わせて、値をカスタマイズして利用してください。

margin-top: calc((0.75 - line-height) * 0.5em)

変数を利用すると使い勝手がよくなります。

@mixin lhCrop($line-height, $capital-letter) {
  &::before {
    content: '';
    display: block;
    height: 0;
    width: 0;
    margin-top: calc((#{$capital-letter} - #{$line-height}) * 0.5em);
  }
}

.text-to-crop {
  @include lhCrop(1.2, 0.75);
}

日本語でも数値を変えれば利用可能です。
demo

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