1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Tailwindでフォントサイズのクラスに付いてくるline-heightを削除する

Last updated at Posted at 2025-01-31

はじめに

Tailwind CSS では、text-* クラスを適用すると font-size だけでなく line-height も一緒に適用されます。
しかし、デザインによってはデフォルトの line-height を適応させたくないケースがあります。
本記事ではその解決方法を紹介します。

:pushpin: 検証バージョン: Tailwind CSS v3.3.0

変更前の動作

デフォルトでは text-* クラスを適用すると、 line-height も一緒に出力されます。

index.tsx
// テストコード
<div>
    <div className="text-xs">text-xs</div>
    <div className="text-sm">text-sm</div>
    <div className="text-base">text-base</div>
    <div className="text-lg">text-lg</div>
    <div className="text-xl">text-xl</div>
    <div className="text-2xl">text-2xl</div>
    <div className="text-3xl">text-3xl</div>
    <div className="text-4xl">text-4xl</div>
    <div className="text-5xl">text-5xl</div>
    <div className="text-6xl">text-6xl</div>
    <div className="text-7xl">text-7xl</div>
    <div className="text-8xl">text-8xl</div>
    <div className="text-9xl">text-9xl</div>
</div>

出力されるCSS

スクリーンショット 2025-01-31 20.34.16.png

line-height を削除する設定

tailwind.config.ts に以下の設定を追加し、 line-height を除外します。

tailwind.config.ts
import type { Config } from "tailwindcss";
const defaultTheme = require('tailwindcss/defaultTheme');
const defaultFontSize = defaultTheme.fontSize;

const config: Config = {
  theme: {
    extend: {
      fontSize: {
        // ここを追加
        ...Object.fromEntries(
          Object.entries(defaultFontSize).map(([key, value]) => [key, (value as [string, object])[0]])
        ),
      },
      // ...
    }
  }
};
export default config;

defaultFontSize には下記のオブジェクトが入っているので、
font-size の値のみを抽出しています。

デフォルト値の参照
https://v3.tailwindcss.com/docs/theme#referencing-the-default-theme

{
    xs: ['0.75rem', { lineHeight: '1rem' }],
    sm: ['0.875rem', { lineHeight: '1.25rem' }],
    base: ['1rem', { lineHeight: '1.5rem' }],
    lg: ['1.125rem', { lineHeight: '1.75rem' }],
    xl: ['1.25rem', { lineHeight: '1.75rem' }],
    '2xl': ['1.5rem', { lineHeight: '2rem' }],
    '3xl': ['1.875rem', { lineHeight: '2.25rem' }],
    '4xl': ['2.25rem', { lineHeight: '2.5rem' }],
    '5xl': ['3rem', { lineHeight: '1' }],
    '6xl': ['3.75rem', { lineHeight: '1' }],
    '7xl': ['4.5rem', { lineHeight: '1' }],
    '8xl': ['6rem', { lineHeight: '1' }],
    '9xl': ['8rem', { lineHeight: '1' }],
} 

変更後の動作

line-height が削除され、 font-size のみが適用されるようになりました。

スクリーンショット 2025-01-31 20.35.27.png

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?