Home > Net >  Add gradient as a class in Tailwind css
Add gradient as a class in Tailwind css

Time:10-04

I want to add this style:

background: linear-gradient(10deg, #AF8800 4.03%, #AA9F1F 6.02%, #A7B334 6.01%)

... to tailwind to be able to add it as a class name. I know that in tailwind we can create classes like this:

bg-[red]

Question: How to do the same action as above with the specified gradient?

CodePudding user response:

you can easily use from and to in your class like

<div ></div>

from that's snippet you can gradient from color cyan 500, to blue 500

CodePudding user response:

It is complex gradient so you have to use either arbitrary values or extend Tailwind configuration. Add CSS property almost as it is within square brackets - replace spaces with low dash _. Your class should looks like

<div ></div>

If you have less than 3 colors included it may be separated between few "stop-color" classes

<div ></div>

I've also created this package so you can use bg-gradient-10 instead of bg-[linear-gradient(10deg,var(--tw-gradient-stops))]

If you want to avoid arbitrary variants you may extend configuration for background-image or create static utility plugin

const plugin = require('tailwindcss/plugin')

/** @type {import('tailwindcss').Config} */
module.exports = {
  theme: {
    extend: {
      backgroundImage: {
        'my-gradient': 'linear-gradient(10deg, #AF8800 4.03%, #AA9F1F 6.02%, #A7B334 6.01%)'
      }
    },
  },
  plugins: [
     plugin(function({ addUtilities, addComponents, e, config }) {
      addUtilities({
        '.bg-my-uitility-gradient': {
          'background-image': 'linear-gradient(10deg, #AF8800 4.03%, #AA9F1F 6.02%, #A7B334 6.01%)',
        },
      })
    })
  ],
}
<div ></div>

<div ></div>

DEMO

  • Related