How to build a static blog part 8

Saturday, 8 July 2023

Light and dark modes

It's great, in my opinion, that so many websites and products are offering their interfaces in a light or dark version these days. Nuxt and Tailwind both have a nice solution to implementing a dark mode on your site, without much effort.

Create a new file in your components folder called ColorModeSwitch.vue.

<script setup>
// Not using ts here as there is an issue with
// types on Nuxt's Color Mode component. See

const colorMode = useColorMode()
const onClick = () =>
    colorMode.value === 'light'
        ? (colorMode.preference = 'dark')
        : (colorMode.preference = 'light')

        aria-label="Colour Mode"
        class="w-5 h-5 hover:text-sky-500 transition flex flex-col justify-center"
        <ColorScheme placeholder="...">
                v-if="colorMode.value === 'dark'"
                class="w-5 h-5 dark:text-white dark:hover:text-sky-500"
                class="w-5 h-5 dark:text-white dark:hover:text-sky-500"

Insert it into the SiteHeader.vue component, inside the nav, like this

    <nav class="flex items-center py-3 px-1 flex-wrap max-w-2xl mx-auto">
        <ColorModeSwitch></ColorModeSwitch> // <-- here!

That's it! you should have a working colour mode toggle, and the site will react to whatever preference the user has. Some of the setup to get this working can be found in the Nuxt and Tailwind config files, as I’ve already added it. See below.

// nuxt.config.js
colorMode: {
    // Get Nuxt color-mode to work with Tailwind classes
        classSuffix: '',
// tailwind.config.js on line 35
    darkMode: 'class',

Then to specify a style to be applied to dark mode only, you can do this:

<p class="text-black dark:text-white"></p>

This would be black text, unless dark mode is active, then it would be white text.

Next post →

go back