How to build a static blog part 8
Saturday, 8 July 2023Light 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
// https://github.com/nuxt-modules/color-mode/issues/182
const colorMode = useColorMode()
const onClick = () =>
colorMode.value === 'light'
? (colorMode.preference = 'dark')
: (colorMode.preference = 'light')
</script>
<template>
<button
aria-label="Colour Mode"
class="w-5 h-5 hover:text-sky-500 transition flex flex-col justify-center"
@click="onClick"
>
<ColorScheme placeholder="...">
<Icon
v-if="colorMode.value === 'dark'"
name="ph:moon-bold"
class="w-5 h-5 dark:text-white dark:hover:text-sky-500"
/>
<Icon
v-else
name="ph:sun-bold"
class="w-5 h-5 dark:text-white dark:hover:text-sky-500"
/>
</ColorScheme>
</button>
</template>
Insert it into the SiteHeader.vue
component, inside the nav, like this
<template>
<nav class="flex items-center py-3 px-1 flex-wrap max-w-2xl mx-auto">
<ColorModeSwitch></ColorModeSwitch> // <-- here!
</nav>
</template>
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.