Ask any question about CSS here... and get an instant response.
How do I toggle between light and dark mode using CSS variables without JavaScript?
Asked on Dec 09, 2025
Answer
You can toggle between light and dark mode using CSS variables by leveraging the `:root` selector and the `:checked` pseudo-class on a checkbox input. This method allows you to switch themes using only CSS.
<!-- BEGIN COPY / PASTE -->
<style>
:root {
--bg-color: white;
--text-color: black;
}
[data-theme="dark"] {
--bg-color: black;
--text-color: white;
}
body {
background-color: var(--bg-color);
color: var(--text-color);
transition: background-color 0.3s, color 0.3s;
}
input[type="checkbox"] {
display: none;
}
label {
cursor: pointer;
padding: 10px;
background-color: #ccc;
border-radius: 5px;
}
input[type="checkbox"]:checked ~ body {
background-color: var(--bg-color);
color: var(--text-color);
}
</style>
<input type="checkbox" id="theme-toggle">
<label for="theme-toggle">Toggle Theme</label>
<!-- END COPY / PASTE -->Additional Comment:
- The `:root` selector defines default CSS variables for light mode.
- The `[data-theme="dark"]` attribute selector changes the CSS variables for dark mode.
- The checkbox input is hidden but used to toggle the theme when checked.
- The `label` element is styled to act as a toggle button.
- CSS transitions are used for smooth color changes.
Recommended Links:
