Skip to main content

Auto Dark Mode with CSS

How to automatically switch between light and dark themes in your CSS based on the visitors system settings.

If you want your site to automatically switch between light and dark themes based on the visitor's system settings, you can use a @media query and the prefers-color-scheme feature.

css:root {
    --color-background: #eee;
    --color-text: #000;
}

@media (prefers-color-scheme: dark) {
    :root {
        --color-background: #333;
        --color-text: #eee;
    }
}

body {
    color: var(--color-text);
    background-color: var(--color-background);
}
Updated on Jul 30, 2025