【Tailwind CSS】px数や角度など独自の値を設定する方法

2024.07.10

Tailwindはユーティリティクラスというあらかじめあるクラス名をhtmlタグに指定することでstyleを効かせることができます。ただ、デフォルトでは決まった数値しか設定されておらず細かく表示を調整することができません。

Tailwind.config.jsに値を設定する方法

これを解消するにはtailwind.config.jsに記述することで自分の使いたい値を設定することができます。

module.exports = {
  content: [
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
  theme: {
    extend: {
      rotate: {
        '15': '15deg',
        '30': '30deg',
        '60': '60deg',
        '120': '120deg',
        '270': '270deg',
        '375': '375deg',
        '390': '390deg',
        '405': '405deg',
        // 他の必要なカスタム角度を追加
      },
      screens: {
        'max-sm': {'max': '640px'},  // 640px以下の設定
        'max-md': {'max': '768px'},  // 768px以下の設定
      },
    },
  },
  plugins: [],
}

extendの項目で追加をしています。上記はrotateの値とメディアクエリの値を設定しています。これで作成したクラスをタグに直接記述して使えるようになります。

設定した値は下記のように使います。
設定した「max-sm、max-md、rotate-15」をクラスとして使えるようになりました。

const ResponsiveExample = () => {
  return (
    <div>
      <div className="p-4 max-sm:bg-red-500 rotate-15">
        This box is blue on larger screens and red on screens 640px or smaller.
      </div>
      <div className="p-4 max-md:bg-yellow-500 rotate-15">
        This box is green on larger screens and yellow on screens 768px or smaller.
      </div>
    </div>
  );
}

もっと簡単に指定したい

「configで設定するのめんどくさいよ…」と思い他にないか調べたら、もっといい方法がありました。

px-[20px]というふうに任意の値を括弧で指定する方法があるようです。下記はいくつか例です。

マージン

<div class="m-[20px]">Margin of 20px</div>

ボーダー幅

<div class="border-[5px] border-solid border-black">Border width of 5px</div>

フォントサイズ

<div class="text-[24px]">Font size of 24px</div>

幅と高さ

<div class="w-[300px] h-[300px]">Width and height of 300px</div>

色(RGB値やHex値)

<div class="bg-[#ff5733]">Background color using hex value</div>
<div class="text-[rgb(255,87,51)]">Text color using RGB value</div>

シャドウ

<div class="shadow-[0px_4px_10px_rgba(0,0,0,0.25)]">Custom shadow</div>

z-index

<div class="z-[999]">z-index of 999</div>

行の高さ

<div class="leading-[1.5]">Line height of 1.5</div>

レター間隔

<div class="tracking-[2px]">Letter spacing of 2px</div>

その他

<div class="mt-[10px] mb-[30px]">Margin top of 10px and margin bottom of 30px</div>
<div class="p-[15px]">Padding of 15px</div>
<div class="w-[50%] h-[200px]">Width of 50% and height of 200px</div>
<div class="text-[12pt]">Font size of 12pt</div>
<div class="rounded-[10px]">Border radius of 10px</div>
<div class="opacity-[0.7]">Opacity of 0.7</div>
<div class="translate-y-[20%]">Translate Y of 20%</div>
<div class="rotate-[45deg]">Rotation of 45 degrees</div>

こちらの使い方の方が便利ですね。
基本的にはTailwind CSSのユーティリティクラスが存在するプロパティであれば指定できるようです!

totop Page Top