ollie_123's avatar

Vite & Switching Themes

Evening All,

I'm working on a project where the project calls for switchable themes for each user.

I can create multiple CSS files and run build on them but....before Laravel 9, i could do this by using an if condition using the authenticated user and adding the relevant CSS files within the condition but in vite as all CSS files are called in vite([...]) in the layout file & in the vite.config.js file i'm not sure how best to switch this.

I was thinking of doing an if condition with different css files in vite([...]) but thought maybe someone knows of a better way?

Any advice would be greatly appreciated.

Thanks all.

0 likes
6 replies
ollie_123's avatar

Hey @sinnbeck, thanks for the suggestion.

The only thing is, DaisyUI looks to store in local storage which would be cleared once the user leaves the site & i'm looking to store the users choice in the DB and serve the relevant CSS file based on their choice as i'm not primarily using tailwind.

Thanks in advance.

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

@ollie_123 haven't used it yet (plan to in my next project). But as I understand it, you can just set it in the body. No need for local storage

<html data-theme="{{$theme}}"></html>
1 like
ollie_123's avatar

Thanks @sinnbeck, i see what you're getting at....

Looking at the github docs and using your suggesting, adding the following to all of the CSS classes then changes the styling accordingly upon refresh when the user selects a different theme.

/* e.g main.css */
[data-theme='light'] .bg-primary {
	background-color: var(--light-grey);
}
[data-theme='dark'] .bg-primary {
	background-color: var(--dark-grey);
}

Interesting as this doesn't even require DaisyUI.

Looks like i've got some work to do standardising and adding classes. This does mean a much larger CSS file being called the more styles are added. I imagine this will increase load times but hope minifying the CSS file helps to reduce that.

Thanks for steering me in the right direction. :)

Sinnbeck's avatar

@ollie_123 happy to help. And remember that the browser caches the file, so even if it is slightly bigger, it's only downloaded once

1 like
ollie_123's avatar

@Sinnbeck very good point. Thank you.

In the end to keep the code cleaner i ended up creating a base file with all of the styling and then creating separate light / dark etc css files which targets the colours only.

Thanks again :)

Please or to participate in this conversation.