Tailwind CSS variables based on light/dark mode

I'm importing my Sass styling into Tailwind and the structure is roughly
<button class="some-section">
</button>

<style lang="scss">
:root {
--button-bg: some-color;
}

@media (prefers-color-scheme: dark) {
:root {
--button-bg: other color;
}
}

.some-section {
background-color: var(--button-bg);
}
</style>
<button class="some-section">
</button>

<style lang="scss">
:root {
--button-bg: some-color;
}

@media (prefers-color-scheme: dark) {
:root {
--button-bg: other color;
}
}

.some-section {
background-color: var(--button-bg);
}
</style>
I have another section in my Chrome extension that has a toggle, something like
<script lang="ts">
let theme: "light" | "dark" : "auto";
const isPageDark = () => document.body.getAttribute("dark") !== null;
let themeCurrent: "light" | "dark" = isPageDark() ? "dark" : "light";

$: if (theme === "auto") {
themeCurrent = isPageDark() ? "dark" : "light";
}
new MutationObserver(() => {
if (theme === "auto") {
themeCurrent = isPageDark() ? "dark" : "light";
}
}).observe(document.body, { attribtes: true, attributeFilter: ["dark"] })
</script>

<button on:click={() => theme = "light"}Light theme</button>
<button on:click={() => theme = "dark"}>Dark theme</button>
<button on:click={() => theme = "auto"}>Auto</button>

<main data-theme={themeCurrent}>
</main>

<style lang="scss">
[data-theme="light"] {
--bg: some-color;
}

[data-theme="dark"] {
--bg: some-other-color;
}

main {
background-color: var(--bg);
}
</style>
<script lang="ts">
let theme: "light" | "dark" : "auto";
const isPageDark = () => document.body.getAttribute("dark") !== null;
let themeCurrent: "light" | "dark" = isPageDark() ? "dark" : "light";

$: if (theme === "auto") {
themeCurrent = isPageDark() ? "dark" : "light";
}
new MutationObserver(() => {
if (theme === "auto") {
themeCurrent = isPageDark() ? "dark" : "light";
}
}).observe(document.body, { attribtes: true, attributeFilter: ["dark"] })
</script>

<button on:click={() => theme = "light"}Light theme</button>
<button on:click={() => theme = "dark"}>Dark theme</button>
<button on:click={() => theme = "auto"}>Auto</button>

<main data-theme={themeCurrent}>
</main>

<style lang="scss">
[data-theme="light"] {
--bg: some-color;
}

[data-theme="dark"] {
--bg: some-other-color;
}

main {
background-color: var(--bg);
}
</style>
How do I make the equivalent in Tailwind?
2 Replies
Matvey
Matvey8mo ago
Simple dark mode support with Tailwind & CSS variables - Invertase
Using CSS variables you can easily create a custom set of Tailwind classes to easily support dark mode.
Avi
Avi8mo ago
Thanks! Though someone provided me with a better solution:
<main class="bg-[var(--bg)]"></main>
<main class="bg-[var(--bg)]"></main>
Want results from more Discord servers?
Add your server