7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[SCSS/Mixin]テキストのline-heightでできてしまうの余白を先頭と最後の行だけ取り除く

Posted at

line-heightで先頭と最後も余白が入ってむかつく :frowning2:

XDでこういった余白が設定されていたとします。

行間(line-height)は、デザインでは文字サイズが16pxに対して行間が48pxなので
行間48px÷文字16px=3と計算しline-height:3;を設定。
余白(margin-top)は50pxを設定。
それがこちら:writing_hand:


See the Pen
line-heightの余白がムカつく
by himeka223 (@himeka223)
on CodePen.


デザインにしっかり合わせたはずなのに、余白めっちゃ開いちゃってます。
むかつきますね。:frowning2:

これは、line-heightにより先頭と最後も余白が入っちゃっているからです。
最初のデザインがこんな感じでつくられちゃってます:frowning2:

じゃあ、50pxからline-heightでできちゃった先頭と最後の余白分をひいてうまいことやれば、、、:robot:
、、、毎回そんな事考えていたら超大変です。

最強そうな Mixin を見つける :raised_hands:

なにか方法ないかなあと探していたらこんな記事を見つけました。
[CSS]テキスト要素の先頭行だけline-heightを取り除き、上ぴったりに揃えるスタイルシートのテクニック | コリス

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


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

まさに私が探し求めていたものです!
記事ではなにやら難しい話ししてますが、私はシンプルに使いたいので、
とりあえずこのMxinで使ってみます!

かんたんに説明すると:point_up:

before要素のmargin-topに指定したネガティブマージンで
line-heightでできてしまった先頭行の余白を相殺しています!

相殺する値の計算はcalcで行っていて、

1 - #{$line-height}) * 0.5em
  1. $capital-letterはデフォルトは1で、font-size=フォントの高さの場合(font-sizeの75%の高さのフォントなら.75
  2. $line-heighは引数で設定したテキストのline-height
  3. 1.から2.をひくとテキスト1行分の、上と下の余白を足した数になります
  4. 3.× 0.5emすることで、上のみの余白数をだします

マイナスの値になるので、そのまま相殺しています!

少し改良:point_up:

このままだと、先頭行の余白しか相殺してくれてないので、最終行も余白をafter要素で削っちゃいます。
さらにoverflow:hidden;で相殺された余白分をカット**させる。

@mixin lhCrop($line-height:$base-line-height, $capital-letter: 1) {
  overflow:hidden; //相殺した余白をカット
  &::before {
    content: '';
    display: block;
    height: 0;
    width: 0;
    margin-top: calc((#{$capital-letter} - #{$line-height}) * 0.5em);
  }
&::after{
//最終行も取り除く
    content: '';
    display: block;
    height: 0;
    width: 0;
    margin-top: calc((#{$capital-letter} - #{$line-height}) * 0.5em);
}
}

overflow:hidden;でカットしたことで、どこかでやりづらくなりそうな気もするけど、とりあえずカット。(そうなったとき考える)

さっそくさっきのコードにつけてみます:relaxed:

See the Pen Mixin lhCrop by himeka223 (@himeka223) on CodePen.

きれいに余白が潰れました!

まだまだもとの記事を解読する必要もありますが、とりあえずはこれで使ってみます!
これで少しでもコーディングのスピードと精度が上がると嬉しいです:santa_tone4:

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?