
Dark Mode in a couple of CSS Lines. https://codewithdrzeeshanbhatti.com/
Discover how to implement Dark Mode in your web projects with just a few lines of CSS! This guide breaks down the simplest approach to create a sleek and user-friendly dark mode toggle. Learn the magic of CSS variables, media queries, and theming techniques to enhance your website’s visual appeal and user experience. Perfect for beginners and pros alike, this post will have you designing dark mode like a pro in no time!
Introduction:
Dark mode has taken the digital world by storm, offering a stylish, eye-friendly alternative for web design. But did you know you can implement it effortlessly with just a few lines of CSS? In this blog, we’ll show you the easiest way to add dark mode to your website using CSS variables and media queries. Whether you’re building a personal portfolio or a full-scale web app, this quick guide will help you deliver a modern and professional dark mode experience in no time. Let’s dive in!
The CSS Dark Mode
Implementing dark mode on your website can be incredibly simple with just a few lines of CSS. Here’s a breakdown of the code you provided and how it works:
root {
--bg-color: white;
--text-color: black;
}
@media (prefers-color-scheme: dark) {
:root {
--bg-color: black;
--text-color: white;
}
}
body {
background-color: var(--bg-color);
color: var(--text-color);
}
Explanation of CSS code:
- CSS Variables:
- The
:root
selector targets the highest level of the document tree, which is the<html>
element. - Inside
:root
, we define two CSS variables:--bg-color
and--text-color
. Initially, these are set towhite
andblack
, respectively.
- The
- Media Query for Dark Mode:
- The
@media (prefers-color-scheme: dark)
query checks if the user has set their system to dark mode. - If dark mode is preferred, the variables
--bg-color
and--text-color
are redefined toblack
andwhite
, respectively.
- The
- Applying the Variables:
- In the
body
selector, we use thevar()
function to apply the CSS variables.background-color
is set tovar(--bg-color)
andcolor
is set tovar(--text-color)
. - This means that the background and text colors of the body will change based on the user’s preferred color scheme.
- In the
How It Works:
- When the page loads, the initial values of
--bg-color
and--text-color
are applied, setting the background to white and the text to black. - If the user has dark mode enabled on their device, the media query will trigger, and the values of
--bg-color
and--text-color
will switch to black and white, respectively. - This dynamic change ensures that your website adapts to the user’s system preferences without needing any JavaScript.
This approach is efficient and leverages modern CSS features to provide a better user experience. Happy coding! 😊
Is there anything else you’d like to know about CSS or web development? LEAVE A Comment below