css - Dark Mode Using CSS variables
CSS Dark Mode is a current UI element that allows users to toggle between light and dark themes on a website. It is frequently used to alleviate eye strain, increase readability in low light, and conserve battery life on gadgets. Dark Mode may be easily and efficiently implemented with minimal code by utilising CSS variables.
1.What is dark mode in CSS?
- Dark Mode is a design style that involves:
- The background colours are dark.
- Text colours are light.
- The brightness is decreased for comfortable viewing
Using CSS variables, we can:
- Change the complete theme with a single class or attribute.
- Avoid rewriting CSS.
- Create sophisticated UI designs with ease.
2. What are CSS variables?
CSS variables are reusable values that can hold colours, typefaces, sizes, and so on.
They are defined as follows:
--variable-name
They are used as follows:
var(--variable-name)
3. Create a Light Theme (Default Mode):
Root { --background-color: white; --text-color: black; --card-color: #f2f2f2; }
Applying the variables:
body {
background-color: var(--bg-color);
color: var(--text-color);
}
.card {
background-color: var(--card-color);
padding: 20px;
}
4. Creating Dark Theme Using Data Attribute:
[data-theme="dark"] {
--bg-color: #121212;
--text-color: white;
--card-color: #1e1e1e;
}
his automatically changes the colors when dark mode is enabled.
5. Switching Between Light and Dark Mode
Using a simple button with JavaScript:
<button onclick="toggleTheme()">Toggle Dark Mode</button>
<script>
function toggleTheme() {
document.body.toggleAttribute("data-theme");
}
</script>
This switches between light and dark theme instantly.
6. Dark Mode Example (HTML + CSS + JS)
<!DOCTYPE html>
<html>
<head>
<style>
:root {
--bg-color: white;
--text-color: black;
}
[data-theme="dark"] {
--bg-color: #121212;
--text-color: white;
}
body {
background: var(--bg-color);
color: var(--text-color);
font-family: Arial;
padding: 20px;
}
button {
padding: 10px 20px;
cursor: pointer;
}
</style>
</head>
<body>
<h2>CSS Dark Mode Example</h2>
<button onclick="toggleTheme()">Toggle Dark Mode</button>
<script>
function toggleTheme() {
document.body.toggleAttribute("data-theme");
}
</script>
</body>
</html>
7. Benefits of CSS Dark Mode.
- Helps reduce eye strain.
- Improves battery life for OLED panels.
- Enhances user experience
- CSS variables make implementation simple.
- Used for modern websites and mobile apps.
- No heavy JavaScript is required.
Conclusion.
CSS Dark Mode CSS Variables are a powerful and current method used on real-world websites. It allows developers to design professional themes with simple, reusable code.