Overview

At their simplest, plugins are just functions that register new styles for Tailwind to inject into the user’s stylesheet. That means that to get started authoring your own plugin, all you need to do is add an anonymous function to the plugins list in your config file:

  1. // ...
  2. module.exports = {
  3. // ...
  4. plugins: [
  5. function({ addUtilities, addComponents, e, prefix, config }) {
  6. // This function is your plugin
  7. },
  8. ],
  9. // ...
  10. }

Plugin functions receive a single object argument that can be destructured into several helper functions:

  • addUtilities(), for registering new utility styles
  • addComponents(), for registering new component styles
  • addVariant(), for registering custom variants
  • e(), for escaping strings meant to be used in class names
  • prefix(), for manually applying the user’s configured prefix to parts of a selector
  • config(), for looking up values in the user’s Tailwind configuration

Adding utilities

The addUtilities function allows you to register new styles to be output (along with the built-in utilities) at the @tailwind utilities directive.

Plugin utilities are output in the order they are registered, after built-in utilities, so if a plugin targets any of the same properties as a built-in utility, the plugin utility will take precedence.

To add new utilities from a plugin, call addUtilities, passing in your styles using CSS-in-JS syntax:

  1. function({ addUtilities }) {
  2. const newUtilities = {
  3. '.skew-10deg': {
  4. transform: 'skewY(-10deg)',
  5. },
  6. '.skew-15deg': {
  7. transform: 'skewY(-15deg)',
  8. },
  9. }
  10. addUtilities(newUtilities)
  11. }

Prefix and important preferences

By default, plugin utilities automatically respect the user’s prefix and important preferences.

That means that given this Tailwind configuration:

  1. // ...
  2. module.exports = {
  3. // ...
  4. options: {
  5. prefix: 'tw-',
  6. important: true,
  7. },
  8. }

…the example plugin above would generate the following CSS:

  1. .tw-skew-10deg {
  2. transform: skewY(-10deg) !important;
  3. }
  4. .tw-skew-15deg {
  5. transform: skewY(-15deg) !important;
  6. }

If necessary, you can opt out of this behavior by passing an options object as a second parameter to addUtilities:

  1. function({ addUtilities }) {
  2. // ...
  3. addUtilities(newUtilities, {
  4. respectPrefix: false,
  5. respectImportant: false,
  6. })
  7. }

Responsive and state variants

To generate responsive, hover, focus, active, or group-hover variants of your styles, specify the variants you’d like to generate using the variants option:

  1. function({ addUtilities }) {
  2. // ...
  3. addUtilities(newUtilities, {
  4. variants: ['responsive', 'hover'],
  5. })
  6. }

If you only need to specify variants and don’t need to opt-out of the default prefix or important options, you can also pass the array of variants as the second parameter directly:

  1. function({ addUtilities }) {
  2. // ...
  3. addUtilities(newUtilities, ['responsive', 'hover'])
  4. }

Adding components

The addComponents function allows you to register new styles to be output at the @tailwind components directive.

Use it to add more opinionated, complex classes like buttons, form controls, alerts, etc; the sort of pre-built components you often see in other frameworks that you might need to override with utility classes.

To add new component styles from a plugin, call addComponents, passing in your styles using CSS-in-JS syntax:

  1. function({ addComponents }) {
  2. const buttons = {
  3. '.btn': {
  4. padding: '.5rem 1rem',
  5. borderRadius: '.25rem',
  6. fontWeight: '600',
  7. },
  8. '.btn-blue': {
  9. backgroundColor: '#3490dc',
  10. color: '#fff',
  11. '&:hover': {
  12. backgroundColor: '#2779bd'
  13. },
  14. },
  15. '.btn-red': {
  16. backgroundColor: '#e3342f',
  17. color: '#fff',
  18. '&:hover': {
  19. backgroundColor: '#cc1f1a'
  20. },
  21. },
  22. }
  23. addComponents(buttons)
  24. }

Prefix and important preferences

By default, component classes automatically respect the user’s prefix preference, but they are not affected by the user’s important preference.

That means that given this Tailwind configuration:

  1. // ...
  2. module.exports = {
  3. // ...
  4. options: {
  5. prefix: 'tw-',
  6. important: true,
  7. },
  8. }

…the example plugin above would generate the following CSS:

  1. .tw-btn {
  2. padding: .5rem 1rem;
  3. border-radius: .25rem;
  4. font-weight: 600;
  5. }
  6. .tw-btn-blue {
  7. background-color: #3490dc;
  8. color: #fff;
  9. }
  10. .tw-btn-blue:hover {
  11. background-color: #2779bd;
  12. }
  13. .tw-btn-blue {
  14. background-color: #e3342f;
  15. color: #fff;
  16. }
  17. .tw-btn-blue:hover {
  18. background-color: #cc1f1a;
  19. }

Although there’s rarely a good reason to make component declarations important, if you really need to do it you can always add !important manually:

  1. function({ addComponents }) {
  2. addComponents({
  3. '.btn': {
  4. padding: '.5rem 1rem !important',
  5. borderRadius: '.25rem !important',
  6. fontWeight: '600 !important',
  7. },
  8. // ...
  9. })
  10. }

All classes in a selector will be prefixed, so if you add a more complex style like:

  1. function({ addComponents }) {
  2. addComponents({
  3. // ...
  4. '.navbar-inverse a.nav-link': {
  5. color: '#fff',
  6. }
  7. })
  8. }

…the following CSS would be generated:

  1. .tw-navbar-inverse a.tw-nav-link {
  2. color: #fff;
  3. }

To opt out of prefixing, pass an options object as a second parameter to addComponents:

  1. function({ addComponents }) {
  2. // ...
  3. addComponents(buttons, {
  4. respectPrefix: false,
  5. })
  6. }

Responsive and state variants

The addComponents function doesn’t provide the ability to automatically generate variants since it doesn’t typically make sense to do so for component classes.

You can always do this manually if necessary by wrapping your styles in the @variants at-rule:

  1. function({ addComponents }) {
  2. addComponents({
  3. '@variants responsive, hover': {
  4. '.btn': {
  5. padding: '.5rem 1rem !important',
  6. borderRadius: '.25rem !important',
  7. fontWeight: '600 !important',
  8. },
  9. // ...
  10. }
  11. })
  12. }

Escaping class names

If your plugin generates classes that contain user-provided strings, you can use the e function to escape those class names to make sure non-standard characters are handled properly automatically.

For example, this plugin generates a set of .rotate-{angle} utilities where {angle} is a user provided string. The e function is used to escape the concatenated class name to make sure classes like .rotate-1/4 work as expected:

  1. function({ e, addUtilities }) {
  2. const angles = {
  3. '1/4': '90deg',
  4. '1/2': '180deg',
  5. '3/4': '270deg',
  6. }
  7. const rotateUtilities = _.map(angles, (value, key) => {
  8. return {
  9. [`.${e(`rotate-${key}`)}`]: {
  10. transform: `rotate(${value})`
  11. }
  12. }
  13. })
  14. addUtilities(rotateUtilities)
  15. }

This plugin would generate the following CSS:

  1. .rotate-1\/4 {
  2. transform: rotate(90deg);
  3. }
  4. .rotate-1\/2 {
  5. transform: rotate(180deg);
  6. }
  7. .rotate-3\/4 {
  8. transform: rotate(270deg);
  9. }

Be careful to only escape content you actually want to escape; don’t pass the leading . in a class name or the : at the beginning pseudo-classes like :hover or :focus or those characters will be escaped.

Additionally, because CSS has rules about the characters a class name can start with (a class can’t start with a number, but it can contain one), it’s a good idea to escape your complete class name (not just the user-provided portion) or you may end up with unnecessary escape sequences:

  1. // Will unnecessarily escape `1`
  2. `.rotate-${e('1/4')}`
  3. // => '.rotate-\31 \/4'
  4. // Won't escape `1` because it's not the first character
  5. `.${e('rotate-1/4')}`
  6. // => '.rotate-1\/4'

Manually prefixing selectors

If you’re writing something complex where you only want to prefix certain classes, you can use the prefix function to have fine-grained control of when the user’s configured prefix is applied.

For example, if you’re creating a plugin to be reused across a set of internal projects that includes existing classes in its selectors, you might only want to prefix the new classes:

  1. function({ prefix, addComponents }) {
  2. addComponents({
  3. [`.existing-class > ${prefix('.new-class')}`]: {
  4. backgroundColor: '#fff',
  5. },
  6. })
  7. }

Assuming a configured prefix of tw-, this would generate the following CSS:

  1. .existing-class > .tw-new-class {
  2. background-color: #fff;
  3. }

The prefix function will prefix all classes in a selector and ignore non-classes, so it’s totally safe to pass complex selectors like this one:

  1. prefix('.btn-blue .w-1\/4 > h1.text-xl + a .bar')
  2. // => '.tw-btn-blue .tw-w-1\/4 > h1.tw-text-xl + a .tw-bar'

Referencing the user’s config

The config function allows you to ask for a value from the user’s Tailwind configuration using dot notation, providing a default value if that path doesn’t exist.

For example, this simplified version of the built-in container plugin uses the config function to get the user’s configured breakpoints:

  1. function({ addComponents, config }) {
  2. const screens = config('screens', [])
  3. const mediaQueries = _.map(screens, width => {
  4. return {
  5. [`@media (min-width: ${width})`]: {
  6. '.container': {
  7. 'max-width': width,
  8. },
  9. },
  10. }
  11. })
  12. addComponents([
  13. { '.container': { width: '100%' } },
  14. ...mediaQueries,
  15. ])
  16. }

Avoid relying too heavily on using the config function as a way to make your plugin customizable; it’s much better to accept configuration options explicitly.

Use the config function as a convenience to the end-user when it makes sense to use their existing configuration values by default, but always provide explicit options that allow the user to configure your plugin directly as well.

Exposing options

It often makes sense for a plugin to expose its own options that the user can configure to customize the plugin’s behavior.

The best way to accomplish this is to design your plugins as functions that accept configuration and return another function that has access to that configuration from the parent scope.

For example, here’s a plugin (extracted to its own module) for creating simple gradient utilities that accepts the gradients and variants to generate as options:

  1. const _ = require('lodash')
  2. module.exports = function({ gradients, variants }) {
  3. return function({ addUtilities, e }) {
  4. const utilities = _.map(gradients, ([start, end], name) => ({
  5. [`.bg-gradient-${e(name)}`]: {
  6. backgroundImage: `linear-gradient(to right, ${start}, ${end})`
  7. }
  8. }))
  9. addUtilities(utilities, variants)
  10. }
  11. }

To use it, you’d require it in your plugins list, passing through your gradients and variants:

  1. // ...
  2. module.exports = {
  3. // ...
  4. plugins: [
  5. require('./path/to/plugin')({
  6. gradients: {
  7. 'blue-green': [colors['blue'], colors['green']],
  8. 'purple-blue': [colors['purple'], colors['blue']],
  9. // ...
  10. },
  11. variants: ['responsive', 'hover'],
  12. })
  13. ],
  14. // ...
  15. }

There’s no rules about how your plugin needs to be configured; you are in total control of the options you expose and how they work. Tailwind only cares about the actual plugin function you return when it’s all said and done.

CSS-in-JS syntax

Both addUtilities and addComponents expect CSS rules written as JavaScript objects. Tailwind uses the same sort of syntax you might recognize from CSS-in-JS libraries like Emotion, and is powered by postcss-js under the hood.

Consider this simple CSS rule:

  1. .card {
  2. background-color: #fff;
  3. border-radius: .25rem;
  4. box-shadow: 0 2px 4px rgba(0,0,0,0.2);
  5. }

Translating this to a CSS-in-JS object would look like this:

  1. addComponents({
  2. '.card': {
  3. 'background-color': '#fff',
  4. 'border-radius': '.25rem',
  5. 'box-shadow': '0 2px 4px rgba(0,0,0,0.2)',
  6. }
  7. })

For convenience, property names can also be written in camelCase and will be automatically translated to dash-case:

  1. addComponents({
  2. '.card': {
  3. backgroundColor: '#fff',
  4. borderRadius: '.25rem',
  5. boxShadow: '0 2px 4px rgba(0,0,0,0.2)',
  6. }
  7. })

Nesting is also supported, using the same syntax you might be familiar with from Sass or Less:

  1. addComponents({
  2. '.card': {
  3. backgroundColor: '#fff',
  4. borderRadius: '.25rem',
  5. boxShadow: '0 2px 4px rgba(0,0,0,0.2)',
  6. '&:hover': {
  7. boxShadow: '0 10px 15px rgba(0,0,0,0.2)',
  8. }
  9. '@media (min-width: 500px)': {
  10. borderRadius: '.5rem',
  11. }
  12. }
  13. })

Multiple rules can be defined in the same object:

  1. addComponents({
  2. '.btn': {
  3. padding: '.5rem 1rem',
  4. borderRadius: '.25rem',
  5. fontWeight: '600',
  6. },
  7. '.btn-blue': {
  8. backgroundColor: '#3490dc',
  9. color: '#fff',
  10. '&:hover': {
  11. backgroundColor: '#2779bd'
  12. },
  13. },
  14. '.btn-red': {
  15. backgroundColor: '#e3342f',
  16. color: '#fff',
  17. '&:hover': {
  18. backgroundColor: '#cc1f1a'
  19. },
  20. },
  21. })

…or as an array of objects in case you need to repeat the same key:

  1. addComponents([
  2. {
  3. '@media (min-width: 500px)': {
  4. // ...
  5. }
  6. },
  7. {
  8. '@media (min-width: 500px)': {
  9. // ...
  10. }
  11. },
  12. {
  13. '@media (min-width: 500px)': {
  14. // ...
  15. }
  16. },
  17. ])

Adding variants

The addVariant function allows you to register your own custom variants that can be used just like the built-in hover, focus, active, etc. variants.

To add a new variant, call the addVariant function, passing in the name of your custom variant, and a callback that modifies the affected CSS rules as needed.

  1. function({ addVariant }) {
  2. addVariant('disabled', ({ modifySelectors, separator }) => {
  3. modifySelectors(({ className }) => {
  4. return `.disabled${separator}${className}:disabled`
  5. })
  6. })
  7. }

The callback receives an object that can be destructured into the following parts:

  • modifySelectors, a helper function to simplify adding basic variants
  • separator, the user’s configured separator string
  • container, a PostCSS Container containing all of the rules the variant is being applied to, for creating complex variants

Basic variants

If you want to add a simple variant that only needs to change the selector, use the modifySelectors helper.

The modifySelectors helper accepts a function that receives an object that can be destructured into the following parts:

  • selector, the complete unmodified selector for the current rule
  • className, the class name of the current rule with the leading dot removed

The function you pass to modifySelectors should simply return the modified selector.

For example, a first-child variant plugin could be written like this:

  1. function({ addVariant }) {
  2. addVariant('first-child', ({ modifySelectors, separator }) => {
  3. modifySelectors(({ className }) => {
  4. return `.first-child${separator}${className}:first-child`
  5. })
  6. })
  7. }

Complex variants

If you need to do anything beyond simply modifying selectors (like changing the actual rule declarations, or wrapping the rules in another at-rule), you’ll need to use the container instance.

Using the container instance, you can traverse all of the rules within a given module or @variants block and manipulate them however you like using the standard PostCSS API.

For example, this plugin creates an important version of each affected utility by prepending the class with an exclamation mark and modifying each declaration to be important:

  1. function({ addVariant }) {
  2. addVariant('important', ({ container }) => {
  3. container.walkRules(rule => {
  4. rule.selector = `.\\!${rule.selector.slice(1)}`
  5. rule.walkDecls(decl => {
  6. decl.important = true
  7. })
  8. })
  9. })
  10. }

This plugin takes all of the rules inside the container, wraps them in a @supports (display: grid) at-rule, and prefixes each rule with supports-grid:

  1. const postcss = require('postcss')
  2. function({ addVariant }) {
  3. addVariant('supports-grid', ({ container, separator }) => {
  4. const supportsRule = postcss.atRule({ name: 'supports', params: '(display: grid)' })
  5. supportsRule.nodes = container.nodes
  6. container.nodes = [supportsRule]
  7. supportsRule.walkRules(rule => {
  8. rule.selector = `.supports-grid${separator}${rule.selector.slice(1)}`
  9. })
  10. })
  11. }

To learn more about working with PostCSS directly, check out the PostCSS API documentation.

Using custom variants

Using custom variants is no different than using Tailwind’s built-in variants.

To use custom variants with Tailwind’s modules, add them to the modules section of your config file:

  1. modules.exports = {
  2. // ...
  3. modules: {
  4. // ...
  5. borderWidths: ['responsive', 'hover', 'focus', 'first-child', 'disabled'],
  6. // ...
  7. }
  8. }

To use custom variants with custom utilities in your own CSS, use the variants at-rule:

  1. @variants hover, first-child {
  2. .bg-cover-image {
  3. background-image: url('/path/to/image.jpg');
  4. }
  5. }

Example plugins

To check out a few example plugins, visit the plugin examples repository on GitHub.