Asking
Asking

Reputation: 4192

Add gradient as a class in Tailwind css

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?

Upvotes: 2

Views: 2373

Answers (2)

Ihar Aliakseyenka
Ihar Aliakseyenka

Reputation: 14233

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 class="bg-[linear-gradient(10deg,#AF8800_4.03%,#AA9F1F_6.02%,#A7B334_6.01%)] p-10"></div>

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

<div class="p-10 bg-[linear-gradient(10deg,var(--tw-gradient-stops))] from-[#AF8800_4.03%] via-[#AA9F1F_6.02%] to-[#A7B334_6.01%]"></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 class="p-10 bg-my-gradient"></div>

<div class="p-10 bg-my-uitility-gradient"></div>

DEMO

Upvotes: 2

aknadif
aknadif

Reputation: 71

you can easily use from and to in your class like

<div class="bg-gradient-to-r from-cyan-500 to-blue-500"></div>

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

Upvotes: 1

Related Questions