LoginSignup
8
5

More than 3 years have passed since last update.

tailwindcssのプラグインを使って、文字に影をつける

Last updated at Posted at 2019-08-16

文字に影つけたいときありますよね

image.png

  <div class="p-4 text-left m-4 shadow">
    <div class="text-shadow mb-2">この文字は、</div>
    <div class="text-shadow-md mb-2">だんだん、、</div>
    <div class="text-shadow-lg mb-2">浮いてきます。。</div>
    <div class="text-shadow-xl mb-2">お。。。</div>
    <div class="text-shadow-2xl mb-2">おおお!?</div>
  </div>

.text-shadowとかがカスタムのクラスです。

Tailwindcssで作る

こんな感じで、5段階つくるとします。

  • .text-shadow
  • .text-shadow-md
  • .text-shadow-lg
  • .text-shadow-xl
  • .text-shadow-2xl

だんだん浮いてきますが、-2xlに至っては、半分悪ふざけですね。

やり方は簡単で、tailwind.config.jspluginsプロパティに関数を追加します。

module.exports = {
  theme: {
    extend: {}
  },
  variants: {},
  plugins: [
    function({ addUtilities }) {
      const newUtilities = {
        ".text-shadow": {
          textShadow: "0px 2px 3px darkgrey"
        },
        ".text-shadow-md": {
          textShadow: "0px 3px 3px darkgrey"
        },
        ".text-shadow-lg": {
          textShadow: "0px 5px 3px darkgrey"
        },
        ".text-shadow-xl": {
          textShadow: "0px 7px 3px darkgrey"
        },
        ".text-shadow-2xl": {
          textShadow: "0px 10px 3px darkgrey"
        },
        ".text-shadow-none": {
          textShadow: "none"
        }
      };

      addUtilities(newUtilities);
    }
  ]
};

解説すると、pluginsに関数を足して、その引数のaddUtilitiesメソッド1を使って、独自のクラスを足しています。

これだけです、お手軽ですね。

パッケージとして公開する

作ったプラグインを、npmに公開したい場合、下記みたいな感じになります。

パッケージ名を、tailwindcss-text-shadow-pluginとした場合

index.js
module.exports = function({ addUtilities }) {
  const newUtilities = {
    ".text-shadow": {
      textShadow: "0px 2px 3px darkgrey"
    },
    ".text-shadow-md": {
      textShadow: "0px 3px 3px darkgrey"
    },
    ".text-shadow-lg": {
      textShadow: "0px 5px 3px darkgrey"
    },
    ".text-shadow-xl": {
      textShadow: "0px 7px 3px darkgrey"
    },
    ".text-shadow-2xl": {
      textShadow: "0px 10px 3px darkgrey"
    },
    ".text-shadow-none": {
      textShadow: "none"
    }
  };

  addUtilities(newUtilities);
};

このindex.jsを作って、package.jsonmainにして、publishしたら、

module.exports = {
  theme: {
    extend: {}
  },
  variants: {},
  plugins: [
    require('tailwindcss-text-shadow-plugin')
  ]
};

という感じで、プラグインを適用することができます。

シンプルでいいですね。

最後の方が急ぎ足でルー大柴みたいになってましたが、伝わったでしょうか。

皆さんもぜひ、便利なプラグインを作って、公開しましょう。


  1. 独自のクラスを作成する方法は、このほかにもaddComponentsaddBaseがあります。詳しくはこちらへどうぞ。 

8
5
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
8
5