Add gradient as a class in Tailwind css - 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?

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

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

Related

Dynamic colors in tailwind css

Is it possible to make the color dynamic in tailwind config.
I want to received the desired color for (primary , accent) from backend via api.
So the user can change the color from the admin panel.
i want to get this hex value from api
Yes this is possible but instead of only primary, you need to return the complete string like bg-primary(as tailwind only recognises the string) where your primary color should be defined in tailwind.config.js file.
For an example you can refer to my answer for this question.
You can try fetching the CSS variables to change you color palette without changing tailwind.config.js
config file:
module.exports = {
theme: {
extend: {
colors: {
"primary": {
100:"var(--primary-color-100)",
200:"var(--primary-color-200)",
},
"accent": "var(--accent-color)"
},
},
},
};
css file:
:root {
--primary-color-100: #fff;
--primary-color-200: #fff00;
--accent-color: #000;
}

Tailwindcss background-image not working in dark mode

I have my Tailwind classes defined like this:
<section class="dark:bg-gray-900 bg-hero-image bg-fixed">
So in the light version a background image is shown and on the dark version just gray-900 as background color.
The image is defined in tailwind.config.js like this:
theme: {
extend: {
backgroundImage: {
'hero-image': "url('/header.jpg')"
},
But this just doesn't work and still shows the image on dark mode.
You have to add backgroundImage to the variants in tailwind.config.js:
module.exports = {
variants: {
extend: {
backgroundImage: ["dark"],
},
},
ALSO you have to add dark:bg-none for the background-image to be set to none.
<section class="dark:bg-gray-900 dark:bg-none bg-hero-image bg-fixed">
This is also nessessary for things like invert and many other classes. Check the corresponding section in the docs, whether or not the variants are included by default.
By default, only responsive variants are generated for invert utilities.
https://v2.tailwindcss.com/docs/invert#variants

TailwindCSS | how to set correct color inside config file to be rendered as RGB/RGBA

Tailwind provides good option to get value from config inside another config object
module.exports = {
theme: {
colors: {
primary: 'red'
},
extend: {
colors: theme => ({
secondary: theme('colors.primary') // will be red
})
}
}
}
But this doesn't work when I want to create classes using RGBA. I want to create something like
module.exports = {
theme: {
colors: {
primary: 'red'
},
extend: {
boxShadow: theme => ({
extra: "0 0 999px rgba(theme('colors.primary'), .25))"
}),
}
}
}
This will render 0 0 999px rgba(red, .25) which is not correct CSS value - you need to pass red as 255, 0, 0. But I want to use colors.primary as it was defined in my config
I know Tailwind has it's own build utils for converting colors like asRgba, withAlphaVariable. For example, when you use text-white Tailwind renders it as color: rgba(255,255,255,var(--tw-text-opacity));. But how can I use it?
So basically how can I achieve this - pass color key from my config into another property and get rendered it as RGB/RGBA?
Update: I want third square (TW) to work as others
DEMO
I think your idea was wrong, because tailwind colors is defined with HEX number, but you trying to use it into RGBA type, so I think you need to convert firstly if you want to make your way.
Anyway let us know your success :)
check this doc

JIT tailwindcss using variable in bg-[] not rendering color

when passing my color as props like this <List text="something" color="#84AB86" /> and using in the code className={'bg-[${color}] '} it does not render properly.
when looking at chrome dev tools color are added correctly like this bg-[#84AB86]
while putting the color manually without taking it from props, it does work correctly
after more testing it seems not possible either to do it like this
const color = "#84CC79"
className={`bg-[${color}]`}
any idea why
To use dynamic classes with JIT tailwind you either need to use safelist config key or create stub file where you list all your dynamic classes that you will use.
Config example:
module.exports = {
content: [
'./pages/**/*.{html,js}',
'./components/**/*.{html,js}',
],
safelist: [
'bg-red-500',
'text-3xl',
'lg:text-4xl',
]
// ...
}
Or make safelist.txt in your src folder, then add classes there just like so:
bg-[#84AB86]
bg-[#fffeee]
// etc..
And don't forget to include this safelist.txt file to your config content so tailwind could watch it.
Explanation from tailwind docs
If you are not using JIT, then you can use safelist option for PurgeCSS:
// tailwind.config.js
module.exports = {
purge: {
// Configure as you need
content: ['./src/**/*.html'],
// These options are passed through directly to PurgeCSS
options: {
// List your classes here, or you can even use RegExp
safelist: ['bg-red-500', 'px-4', /^text-/],
blocklist: [/^debug-/],
keyframes: true,
fontFace: true,
},
},
// ...
}
From the Tailwindcss documentation
Dynamic values Note that you still need to write purgeable HTML when
using arbitrary values, and your classes need to exist as complete
strings for Tailwind to detect them correctly.
Don't use string concatenation to create class names --> <div className={mt-[${size === 'lg' ? '22px' : '17px' }]}></div>
Do dynamically select a complete class name --> <div className={ size === 'lg' ? 'mt-[22px]' : 'mt-[17px]' }></div>
Tailwind doesn’t include any sort of client-side runtime, so class
names need to be statically extractable at build-time, and can’t
depend on any sort of arbitrary dynamic values that change on the
client. Use inline styles for these situations, or combine Tailwind
with a CSS-in-JS library like Emotion if it makes sense for your
project.
As mentioned above tailwind engine In order to render a custom class dynamicaly:
Does not like:
className={`bg-[${custom-color}]-100`}
It expects:
const customBgColorLight = 'bg-custom-color-100';
className={`${customBgColorLight} .....`}
For this to work properly you have to include the name of the class in the safelist:[] in your tailwind.config.js.
For tailwind v.3
/** #type {import('tailwindcss').Config} */
module.exports = {
content: ['./src/**/*.{js,jsx,ts,tsx}'],
safelist: [
'bg-custom-color-500', // your-custom-css-class
'text-custom-color-500',
'border-custom-color-500',
..... // other classes
'hover:bg-custom-color-500', // *** also include it with the selector if needed ***
.... // other classes
],
theme: {
extend: {
colors: {
'custom-color': { // you have to use quotes if key is not in camelCase format
100: '#d6d6d6',
500: '#5E8EA2',
..... //other variants
},
...... // other colors
So you can use it:
// if you want store the values to an object
const yourClassObj = {
customBgColor: 'bg-custom-color-500',
customBrdColor: 'border-custom-color-500',
customTxtColor: 'text-custom-color-500',
};
const { customBgColor, customBrdColor, customTxtColor } = yourClassObj;
<YourComponent
className={`mb-2 font-semibold py-2 px-4 rounded-lg
${ conditionGoesHere ? `${customBgColor} text-white cursor-default`
: `${customTxtColor} border ${customBrdColor}
bg-transparent hover:border-transparent
hover:${customBgColor} hover:text-white`
}`}
/>
An easy solution is to use the built in style property.
For example in React:
Dont Use:
className={`bg-[${color}]`}
Use Instead:
style={{
backgroundColor: color,
}}

Tailwind different themes

I would like to ask if there is any way to use different themes with tailindcss.
Imagine your site has 2 themes - dark and light.
I have a button:
<button class="px-4 bg-blue over:bg-grey-100">Register</button>
This is for the ligth theme.
Is it possible to change the design of the button depending on the theme.
For example in the body i have class: "theme-light" or "theme-dark".
Is it possible to change the classes of the button to apply only for one of the themes.
Something like that theme-dark:bg-orange:
<button class="px-4 bg-blue over:bg-grey-100 theme-dark:bg-orange">Register</button>
If not is there any way to have different themes without writing custom css, or completely rewriting my html pages for the given theme.
If not what's the best way to have 2 or more themes?
Thank you.
It is achievable to have theme-dark and theme-light variants by creating pseudo-class variants. It is detaily described here: https://tailwindcss.com/docs/pseudo-class-variants/#creating-custom-variants
For example, to create theme-dark pseudo-class variant you can do something like this in your tailwind.config.js file:
// tailwind.config.js
const plugin = require('tailwindcss/plugin')
module.exports = {
plugins: [
plugin(function({ addVariant, e }) {
addVariant('theme-dark', ({ modifySelectors, separator }) => {
modifySelectors(({ className }) => {
return `.${e(`theme-dark${separator}${className}`)}:theme-dark`
})
})
})
]
}
You can learn more about this here as well: https://tailwindcss.com/docs/plugins/#adding-variants
However, to achieve what you want, you will need to have some javascript behavior that will have a state from which will be able to tell when it is theme-light and when it is theme-dark, which means this is not achievable with 100% only tailwind.
Also Adam Wathan created quick them of this here: https://github.com/adamwathan/theming-tailwind-demo
I hope this answers your question.
The tw-colors plugin does what you want, the big advantage is that you don't need to use variants.
tailwind.config.js
const { createThemes } = require('tw-colors');
module.exports = {
content: ['./src/**/*.{astro,html,js,jsx,md,mdx,svelte,ts,tsx,vue}'],
plugins: [
createThemes({
halloween: {
'primary': 'orange',
'secondary': 'yellow',
},
summer: {
'primary': 'pink',
'secondary': 'red',
},
winter: {
'primary': 'blue',
'secondary': 'green',
},
party: {
'primary': 'steelblue',
'secondary': 'darkblue',
},
})
],
};
use themes like this with class:
<html class='theme-halloween'>
...
</html>
Or with data attributes:
<html data-theme='halloween'>
...
</html>
Themes can be switched dynamically with some toggle button or whatever you prefer

Resources