This code provides an easy way to implement a dark mode using CSS. It utilizes a checkbox to toggle between light and dark themes, enhancing user experience by adjusting the website’s color scheme with a smooth transition.
You can use this code in your web projects to quickly add a user-friendly dark mode feature. It improves accessibility by allowing users to switch between light and dark themes, enhancing readability in different lighting conditions.
How to Create Easy Dark Mode Using CSS
1. Begin by setting up the HTML structure. Add an input element of type "checkbox"
with the id "switcher"
within your HTML document. This checkbox will serve as the switch for toggling between light and dark modes. Make sure to wrap your website content inside a container, such as a <div>
, with a class name, like “body,” as shown in the provided code.
<input type="checkbox" id="switcher"> <div class="body"> <article> <h1>Hello World</h1> <p>Your content goes here.</p> </article> </div>
2. Next, let’s style our website using CSS. Ensure your website takes up the full viewport height and remove any default margin by applying the styles to the “body” tag. Customize the padding for your content within the “article” element to suit your design preferences.
body { min-height: 100vh; margin: 0; } article { padding: 5em; } .body { display: flex; flex-direction: column; width: 100%; height: 100%; min-height: 100vh; background: white; background-color: var(--bg-color, #fff); color: var(--color, #000); transition: 250ms; } #switcher { position: absolute; -webkit-appearance: none; -moz-appearance: none; appearance: none; top: 1rem; right: 1rem; width: 4em; height: 2em; background-color: var(--color, #000); border-radius: 2em; font-size: 20px; } #switcher::after { position: absolute; top: 0.25em; left: 0.25em; width: 1.5em; height: 1.5em; content: ""; background-color: var(--bg-color, #fff); border-radius: 2em; transform: translateX(var(--translate, 0)); transition: 250ms; } #switcher:checked { --translate: 2em; --bg-color: #424242; --color: #81d4fa; } #switcher:checked ~ * { --bg-color: #424242; --color: #81d4fa; }
That’s all! hopefully, you have successfully integrated this easy Dark Mode using CSS. If you have any questions or suggestions, feel free to comment below.
Similar Code Snippets:
I code and create web elements for amazing people around the world. I like work with new people. New people new Experiences.
I truly enjoy what I’m doing, which makes me more passionate about web development and coding. I am always ready to do challenging tasks whether it is about creating a custom CMS from scratch or customizing an existing system.