Tailwind different themes - tailwind-css

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

Related

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?
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

Override button color in daisy UI?

Daisy UI has buttons: https://daisyui.com/components/button/
However, I'd like to override the colors for a specific button, without having to go through the effort of creating an entire theme.
I can just use bg-green-500 on a button, but that will just change the background color, when I also need to change all of the associated colors.
Is there a good way to do this?
AFAIK, to do this you override the current theme in the tailwind.config.js file.
Note that you import the theme's base:
/** #type {import('tailwindcss').Config} */
module.exports = {
content: ["./app/**/*.{ts,tsx,jsx,js}"],
daisyui: {
themes: [
{
light: {
...require("daisyui/src/colors/themes")["[data-theme=light]"],
primary: "#7cb3dd",
},
},
],
},
plugins: [require("#tailwindcss/typography"), require("daisyui")],
};
Here, we're overriding the primary color to #7cb3dd for the' light' theme.
Adjust as needed!
Here's more info:
https://daisyui.com/docs/themes/

How to change specific elements style in storybook?

In my case I just want to change the default default color, take as example the default home section:
We recommend building UIs with a [**component-driven**](https://componentdriven.org)
That leads to:
I'd like to change that blue to, say, red.
I saw that the a class has the following themes:
class="sbdocs sbdocs-a css-19nbuh3"
So, I created a .storybook/manager-head.html and inside I wrote:
<style>
.sbdocs-a {
color: red;
}
But I see no changes! What am I doing wrong?
You can do this two ways but all in .storybook/preview.js.
Altering the docs theme:
export const parameters = {
...
docs: {
theme: {
colorSecondary: 'red',
},
},
...
};
This have the side effect to cause other unwanted components to change their color, as this color is not used only for links.
Provide your own <a> component to docs [best solution]:
export const parameters = {
...
docs: {
components: {
a: ({children, ...args}) => <a style={{color: 'red'}} {...args}>{children}</a>
},
},
...
};
This is the best way i found to style docs components.
also token name used for a can be found in storybook sources
See theming docs page for a full theme example.

Tailwind css dark mode does not enable

I am trying to enable dark mode based on the system default using tailwind.
To accomplish this I am using the plugin: Tailwind dark mode.
My config fail for tailwind is as follows:
defaultTheme = require('tailwindcss/defaultTheme');
module.exports = {
experimental: {
darkModeVariant: true
},
purge: [],
theme: {
extend: {
fontFamily: {
sans: ['Nunito', ...defaultTheme.fontFamily.sans],
},
screens: {
'dark': {'raw': '(prefers-color-scheme: dark)'},
// => #media (prefers-color-scheme: dark) { ... }
},
},
},
variants: {
backgroundColor: ['dark', 'dark-hover', 'dark-group-hover', 'dark-even', 'dark-odd'],
borderColor: ['dark', 'dark-disabled', 'dark-focus', 'dark-focus-within'],
textColor: ['dark', 'dark-hover', 'dark-active', 'dark-placeholder'],
opacity: ['responsive', 'hover', 'focus', 'disabled']
},
plugins: [require('tailwindcss-dark-mode')()],
}
defaultTheme = require('tailwindcss/defaultTheme');
And in my html file I am adding the following:
<span class="dark:text-yellow-400">
1
</span>
The plugin checks for my dark mode but the text wont turn yellow it stays black.
Does anyone know why it wont work?
First things first, now TailWIndCSS supports dark-mode out-of-the-box by adding the dark: prefix before any class after it is enabled. Not sure if it is related to the question, but thought you need to know.
The plugin you are using states the following use for enabling dark mode:
< tailwind.config.js >
...
plugins: [
require('tailwindcss-dark-mode')()
]
// To enable dark mode for all classes:
variants: ['dark', 'dark-hover', 'dark-group-hover', 'dark-even', 'dark-odd', ...]
// To enable dark mode for only single utility class:
variants: {
backgroundColor: ['dark', 'dark-hover', 'dark-group-hover', 'dark-even', 'dark-odd']
}
...
It also states that
Styles generated by this plugin are only used if the selector is applied to the <html> element. How you do that is up to you. prefers-dark.js is provided as an option, which is a simple script that enables dark mode based on the user's system theme.
So, to enable dark mode through the plugin, use:
< mypage.html >
...
<body class="mode-dark">
<div class="bg-white dark:bg-black">
<p class="text-black dark:text-white">
My eyes are grateful.
<a class="text-blue-300 hover:text-blue-400">
Learn more
</a>
</p>
</div>
...
</body>
Add that extra mode-dark class to the wrapper element (body in this case).
To change the theme based on user preferences through the plugin:
< mypage.html >
<head>
<script src="to/prefers-dark.js"></script>
</head>
...
<body class="mode-dark">
<div class="bg-white dark:bg-black">
<p class="text-black dark:text-white">
My eyes are grateful.
<a class="text-blue-300 hover:text-blue-400">
Learn more
</a>
</p>
</div>
...
</body>
With the above, the theme will change as the user changes his/her preferences in the system settings.
P.S. If you wanna use dark mode, use the one in-built in TailWindCSS v2. Enable it like this:
< tailwind.config.js >
module.exports = {
darkMode: 'media',
...
}
media can be changed to class.
Media: Now whenever dark mode is enabled on the user's operating system, dark:{class} classes will take precedence over unprefixed classes. The media strategy uses the prefers-color-scheme media feature under the hood.
Class: If you want to support toggling dark mode manually instead of relying on the operating system preference, use the class strategy instead of the media strategy.
Hope this helped you :)
I had this problem due to forgetting to update tailwind.config.js:
I changed:
darkMode: false,
to
darkMode: 'class',
I have a simple watcher in Vue that toggles it via:
document.querySelector('html').classList.add('dark')
document.querySelector('html').classList.remove('dark')
You can read more here:
https://tailwindcss.com/docs/dark-mode

Tailwind css backgroundImage doesn't work for me

all,
I'm trying to make tailwinds backgroundImage solution work, and I found help for many other tailwindcss problems here or on github, but not for this.
It's not a complicated task, but still doesn't work.
So as in the documentation, I want to create 2 simple background image to use for multiple viewsize.
It is stated in the documentation https://tailwindcss.com/docs/background-image "By default, only responsive variants are generated for background image utilities."
It means, without any further configuration on variants, I should be able to use it for this purpose.
Here is how my tailwind.conf.js looks like (important part is at the end):
const plugin = require('tailwindcss/plugin')
module.exports = {
purge: [
"./pages/**/*.vue",
"./components/**/*.vue",
"./plugins/**/*.vue",
"./static/**/*.vue",
"./store/**/*.vue"
],
theme: {
extend: {
minHeight: {
'120': '30rem',
},
height: {
'15': '3.75rem',
'17': '4.25rem',
'7': '1.75rem',
'75': '18.75rem',
},
width: {
'15': '3.75rem',
open: '11.875rem',
'75': '18.75rem',
},
margin: {
'7': '1.75rem',
'17': '4.25rem',
'27': '6.75rem',
},
padding: {
'7': '1.75rem',
},
borderWidth: {
'5': '5px',
},
fontSize: {
'5xl': '3.375rem',
'xxl': '1.375rem',
},
boxShadow: {
'lg': '0px 0px 10px #00000033',
'xl': '0px 0px 20px #00000080',
},
gap: {
'7': '1.75rem',
},
inset: {
'10': '2.5rem',
'11': '2.75rem',
'17': '4.25rem',
'1/2': '50%',
},
backgroundImage: {
'hero-lg': "url('/storage/img/sys/lg-hero.jpg')",
'hero-sm': "url('/storage/img/sys/sm-hero.jpg')",
},
}
},
variants: {
opacity: ['group-hover'],
backgroundOpacity: ['group-hover'],
},
plugins: []
}
Just to make sure I included the full content.
And this is how the html looks like:
<div class="bg-hero-sm lg:bg-hero-lg h-24 w-24">
potato
</div>
<div class="h-24 bg-gradient-to-r from-orange-400 via-red-500 to-pink-500"></div>
As I said, nothing special, "npm run dev" finishes witout any error...but if I inspect the element, I cannot see anything related to any background parameter in css. Even the example from documentation doesn't work, which should have to provide a gradient block.
I don't think it's important info, but I use tailwind with laravel.
Can anyone help me with that? I'm desperate, and I'm trying to make it work for days :(I can do workaround using css code in my sass file, but I want to use tailwinds own solution)
Thank you all in advance!
I was having this issue in TailwindCSS 2.2.7 My issue was that my syntax was wrong.
tailwindcss.config.js:
theme: {
backgroundImage: {
'pack-train': "url('../public/images/packTrain.jpg')",
},
App.js
<div className="rounded-lg shadow-lg mb-2 h-screen bg-pack-train flex flex-col sm:mx-8"></div>
The ' and " are critical. For some reason eslint was going in and "cleaning" those characters up on save, which was making it not work. Also, the ../ leading the url was also critical.
If you don't want to extend your theme in the tailwindcss.config.js and want to add the background image directly to your div you can try:
<div className="bg-[url('../public/assets/images/banner.svg')]">
This is the simplest way to get background images working.
Reference: Check under Arbitrary values heading
The background image functionality of tailwindcss has been released in version 1.7.0.
I tested your code in my development environment and it didn't work either since I also had an earlier version of tailwindcss. After upgrading to the latest version, your code has worked fine.
editing your tailwind.config.js
module.exports = {
theme: {
extend: {
backgroundImage: theme => ({
'hero-pattern': "url('/img/hero-pattern.svg')",
'footer-texture': "url('/img/footer-texture.png')",
})
}
}
add name and the URL for your image and use it.
example bg-hero-pattern
u need to add (theme) props to your config
like this:
backgroundImage: (theme) => {
'hero-lg': "url('/storage/img/sys/lg-hero.jpg')",
'hero-sm': "url('/storage/img/sys/sm-hero.jpg')",
},
or url with "../" like this
backgroundImage: (theme) => {
'hero-lg': "url('../storage/img/sys/lg-hero.jpg')",
'hero-sm': "url('../storage/img/sys/sm-hero.jpg')",
},
Hope it works :)
In ^3.1.8 version image path was not working. Then I just put "../" instead of "./"
and it worked. Example:
extend: {
backgroundImage: {
'hero-pattern': "url('../src/assets/images/bg.png')",
}
}
I had to specify a height for my image to be displayed
<div className="h-screen bg-hero"/>
For static image[set is background image] works for me.
First import the image from the static image folder.
import m5 from '../Assets/a2.avif'
Then use it like this.
<div style={{ backgroundImage: `url(${m5})` }}>
module.exports = {content: ["./src/**/*.{html,js}"],theme: {extend{},backgroundImage: {"hero-lg": "url('/src/assets/images/bg.png')","hero-sm": "url('/src/assets/images/bg.png')",},},
class="hero-content bg-hero-sm lg:bg-hero-lg flex-col lg:flex-row-reverse"

Resources