Dark mode
Introduction
The Dark mode component provides a toggle for switching between light and dark color schemes. It uses system preferences, persists user choices, and follows accessibility best practices.
When to use
- Website theming
- User interface customization
- Reducing eye strain in low-light conditions
- Respecting user system preferences
- Battery saving on OLED displays
Usage
Learn how to implement the DarkMode component in your project, from basic usage to advanced configurations.
---import { DarkMode } from 'accessible-astro-components'---
<!-- Default with system preference --><DarkMode />
<!-- With custom icons --><DarkMode> <Icon name="ion:bulb" slot="light" /> <Icon name="ion:bulb-outline" slot="dark" /></DarkMode>
Props
Configure the DarkMode component using these available props to customize its behavior and appearance.
Prop | Type | Default | Description |
---|---|---|---|
initialMode | 'light' | 'dark' | 'auto' | 'auto' | Sets the initial color scheme mode |
label | string | 'Toggle Dark Mode' | Accessible label for the toggle button |
class | string | '' | Additional CSS classes to apply |
Accessibility
Accessibility isn’t an afterthought - it’s built into the core of this component through semantic HTML elements and proper image handling. The DarkMode component is built with accessibility in mind:
- Uses semantic button element
- Proper ARIA attributes (
aria-pressed
,aria-label
) - Maintains focus states
- Persists across page loads using
localStorage
Styling
Make the DarkMode component your own with custom styling while maintaining its accessibility features.
/* Option 1: Using :global() in your style block */<style> :global(.darkmode-toggle) { font-size: 1.125rem; color: light-dark(hsl(215 8% 45%), hsl(215 8% 65%)); }
:global(.darkmode-toggle:hover) { color: light-dark(hsl(215 25% 27%), hsl(215 25% 89%)); }
/* Dark mode styles applied to html element */ :global(.darkmode) { color-scheme: dark; background: hsl(0 0% 10%); color: hsl(0 0% 100%); }</style>
/* Option 2: Using is:global on the style tag */<style is:global> .darkmode-toggle { font-size: 1.125rem; color: light-dark(hsl(215 8% 45%), hsl(215 8% 65%)); }
.darkmode-toggle:hover { color: light-dark(hsl(215 25% 27%), hsl(215 25% 89%)); }
/* Dark mode styles applied to html element */ .darkmode { color-scheme: dark; background: hsl(0 0% 10%); color: hsl(0 0% 100%); }</style>
<DarkMode class="text-lg text-gray-600 hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-100"> <Icon name="ion:sunny" slot="light" class="w-6 h-6" /> <Icon name="ion:moon" slot="dark" class="w-6 h-6" /></DarkMode>
Interactive examples
See the DarkMode component in action with these practical examples demonstrating different variants and styling options.