Ask any question about CSS here... and get an instant response.
How can I automatically switch themes based on the user's dark or light mode preference using CSS?
Asked on Nov 28, 2025
Answer
You can automatically switch themes based on the user's system preference for dark or light mode using CSS media queries. This involves using the `prefers-color-scheme` media feature to apply different styles depending on the user's settings.
<!-- BEGIN COPY / PASTE -->
<style>
body {
background-color: white;
color: black;
}
@media (prefers-color-scheme: dark) {
body {
background-color: black;
color: white;
}
}
</style>
<!-- END COPY / PASTE -->Additional Comment:
- The `prefers-color-scheme` media feature detects if the user prefers a light or dark color theme.
- Define default styles first, then override them within the media query for dark mode.
- This approach ensures that your website respects the user's system-wide theme preference.
Recommended Links:
