2
1

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 で prefix のつく場所が変わった

Last updated at Posted at 2025-02-13

TailwindCSS の知られざるマイナー機能、prefix option についての小ネタです。

prefix option is 何

Tailwind class の prefix を設定できる機能です。
https://tailwindcss.com/docs/styling-with-utility-classes#using-the-prefix-option

エントリーポイントで prefix を指定すると ${prefix}:${tailwindClass} の形で使えるようになります。

style.css
@import "tailwindcss" prefix(tw);
<p class="tw:text-sm">

これの嬉しいポイントは既存の CSS が存在する場合でも痛みなく TailwindCSS を導入しやすいという点です。
既存 CSS で Tailwind のクラスと被る場合でも important battle に発展せず、穏便に済ませることが可能です。
実際、弊社のプロダクト LIFULL HOME'S でも prefix option を使って TailwindCSS を導入しています。

ただ最初から TailwindCSS を導入するのであれば付けるメリットはほぼ皆無です🤪

v3 -> v4 でサイレント破壊的変更された😇

この prefix option は v3 以前にも存在していましたが、v4 とは少し出力が異なります。
設定すると ${prefix}${tailwindClass} の形で使えます。
divider はありませんが、設定で - をつけるのが推奨っぽい。
https://v3.tailwindcss.com/docs/configuration#prefix

tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
  prefix: 'tw-',
}
<p class="tw-text-sm">

一見 prefix と tailwindClass の divider の有無で差分があるだけに見えます。
しかしここに negative value や modifier の概念が入るとややこしくなってきます。

<!-- v4: 全部一律先頭に prefix がつく -->
<p class="tw:-ml-4">
<p class="tw:hover:text-sm">
<p class="tw:hover:-ml-4">

<!-- v3 -->
<p class="-tw-ml-4"> <!-- negative value の時は -${prefix}-${tailwindClass} -->
<p class="hover:tw-text-sm"> <!-- modifier は先頭につく -->
<p class="hover:-tw-ml-4"> <!-- negative value + modifier の時は ${modifier}:-${prefix}-${tailwindClass} -->

表にすると以下のようになります。

パターン prefix なし (~v3/v4共通) prefixあり (~v3) prefixあり (v4~)
通常 text-sm tw-text-sm tw:text-sm
negative value -ml-4 -tw-ml-4 tw:-ml-4
modifier hover:text-sm
hover:-ml-4
hover:tw-text-sm
hover:-tw-ml-4
tw:hover:text-sm
tw:hover:-ml-4

v4 upgrade guide や blog で目玉機能や破壊的変更について触れられていますが、prefix については一切言及がありません😇
アップグレード作業をしているときに diff を見て初めて気づきました🤪
https://tailwindcss.com/docs/upgrade-guide#changes-from-v3
https://tailwindcss.com/blog/tailwindcss-v4

もし現在 Tailwind v3 で prefix を使っている場合は upgrade script を使えばこの辺はよしなに変換されるのでそこは安心です🙏
v3 の prefix ありの記法が体に染み付いているので1日も早く v4 記法に体を慣らしていきたいと思います。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?