Tailwind CSS 4 で text-wrap を使う
Tailwind CSS は v3.4 以降、text-wrap ユーティリティ(text-balance, text-pretty, text-nowrap, text-wrap)を一級クラスとして提供している。
Browser Support
詳細な説明
Tailwind の text-wrap ユーティリティ
Tailwind CSS は v3.4(2024年初頭)で text-wrap ユーティリティを追加し、v4 で改良しました。基となる CSS プロパティに直接マッピングされます:
| ユーティリティ | CSS |
|---|---|
text-wrap |
text-wrap: wrap; |
text-nowrap |
text-wrap: nowrap; |
text-balance |
text-wrap: balance; |
text-pretty |
text-wrap: pretty; |
(text-wrap: stable 用の専用ユーティリティはまだありませんが、@layer utilities で追加できます。)
よくあるパターン
見出し:
<h1 class="text-3xl font-bold text-balance">
Build accessible, performant interfaces without leaving your browser
</h1>
本文段落:
<p class="leading-relaxed text-pretty">
When CSS text-wrap shipped in Chrome 114, designers finally
gained a high-level lever for line breaking...
</p>
ボタン:
<button class="rounded-md bg-blue-600 px-4 py-2 text-white text-nowrap">
Add to Cart
</button>
line-clamp との組み合わせ
Tailwind の line-clamp-N ユーティリティは text-wrap と自然にペアになります:
<h3 class="text-balance line-clamp-2">
Long card title that should balance across two lines maximum
</h3>
<p class="text-pretty line-clamp-3">
Multi-paragraph product description that should be pretty-wrapped
and clamped to three visible lines with an ellipsis...
</p>
レスポンシブバリアント
text-wrap ユーティリティは Tailwind の全レスポンシブバリアントをサポートします。1つのユースケース:見出しが実際に折り返す特定ブレークポイント以上でだけ rebalance する:
<h2 class="text-2xl font-bold md:text-balance">
Different wrapping behavior at md and up
</h2>
(md 未満ではデフォルト折り返し、md 以上で balance を適用。モバイルで見出しが1行に収まる場合に有用。)
カスタム設定
追加の値(stable、カスタムデフォルト)が必要なら tailwind.config.js でテーマを拡張:
module.exports = {
theme: {
extend: {},
},
plugins: [
function({ addUtilities }) {
addUtilities({
'.text-stable': { 'text-wrap': 'stable' },
});
},
],
};
Tailwind 4 の CSS ネイティブ設定
Tailwind 4 では @utility を使って CSS でユーティリティを定義できます:
@utility text-stable {
text-wrap: stable;
}
これで <p class="text-stable"> としてマークアップで使えます。
ユースケース
Tailwind をデザインシステム、マーケティングランディングページ、ダッシュボード UI、EC プラットフォームで使うチーム — 独自クラスを書くより Tailwind ユーティリティで CSS を当てたいあらゆる場面。