4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

TailwindCSS v4 で text-* の line-height の指定値が変わった

Last updated at Posted at 2025-02-13

TailwindCSS v4 リリースされましたね!
Container query など便利な機能が追加されたほか、既存クラスも細かいチューニングがされています。
ただアップグレード作業中に text-* の仕様変更で少しハマってしまったので備忘録として残しておきます。

text-*font-sizeline-height 両方の性質を併せ持つ♣

TailwindCSS は基本的に1クラス1プロパティで構成されていますが、text-* には font-sizeline-height のふたつが指定されています。
たとえば v4 の場合、 .text-xs は以下のような指定になっています。

.text-xs {
  font-size: var(--text-xs); /* 0.75rem (12px) */ 
  line-height: var(--text-xs--line-height); /* calc(1 / 0.75) = 1.33333... */
}

参考:v4ドキュメント font-size - Typography - Tailwind CSS

TailwindCSS の html には line-height: 1.5 が指定されていますが、フォントサイズに応じて適切な line-height を設定することで可読性の高いテキストが表示されるようになっています。

ところがこの line-height, v3 のときは rem で指定されていました。

.text-xs {
  font-size: 0.75rem; /* 12px */
  line-height: 1rem; /* 16px */
}

参考:v3ドキュメント Font Size - Tailwind CSS

倍率と rem の指定の違いはありますが実数値は同じになるため、 line-height の差分は発生しません。
v4 は 12px * calc(1/0.75) = 16px,
v3 は 1rem = 16px になります。

See the Pen 砂場 by Moeko Ebisawa (@ebisawa-next) on CodePen.

ただし親から .text-* を継承 + 子要素で font-size の Arbitrary value を使うと表示が変わる

親にはベースとなる .text-* を指定したが、子要素の一部分で文字サイズを変えたいということはよくあります。
トークンに該当する font-size があればそれを使えばいいのですが、ない場合は Arbitrary value で .text-[1.625rem] のように指定する必要があります。
しかし Arbitrary value で font-size を指定すると line-height は設定されないので、自動的に親の設定を継承します。
v4 では文字サイズに倍率をかけて line-height が決定されるので表示が崩れることはありませんが、v3 では rem で決めうちになっているため値によっては表示崩れの原因となります。

以下は親に .text-xs を、子要素に Arbitrary value で font-size: 1.625rem (26px) を指定した例です。
v4 は 26px * calc(1/0.75) = 34.667px となりましたが、v3 は 1rem = 16px のままなので表示差分が発生しました。

See the Pen 親に text-xs を指定 + 子に Arbitrary value で font-size: 1.625rem を指定 by Moeko Ebisawa (@ebisawa-next) on CodePen.

複数の font-size が入り乱れているコンポーネントがある場合は注意しましょう⚠️

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?