Oteto Blogのロゴ

【SCSS】line-heightによる上下の余白を@mixinで消す

やりたいこと

Adobe XDの行送りと違ってCSSのline-heightには上下の余白が含まれてしまうので、それを消したい。

解決法

mixin

// line-heightによる上下の余白を消す
@mixin remove-line-height-space($line-height) {
  &::before,
  &::after {
    display: block;
    width: 0;
    height: 0;
    content: "";
  }

  &::before {
    margin-top: (1 - $line-height) * 0.5em;
  }

  &::after {
    margin-bottom: (1 - $line-height) * 0.5em;
  }
}

擬似要素それぞれにネガティブマージンをあてて上下の余白を消す。

使用例

@use "xxx" as mixin;

.hoge {
  line-height: 1.7;
  @include mixin.remove-line-height-space(1.7);
}

ただ擬似要素とはいえネガティブマージンを当てるのは応急処置感が強いので、もっと良い方法があるかも。