If you like reading about JavaScript and web-development, you can read about “ What’s the difference between Event Handlers & addEventListener in JS?” or “ 10 JavaScript One-liners You Have Got to Add Your Arsenal as a Developer”. In this tutorial, we’re going to build a toggle that allows users to switch between light and dark modes, using a For a little more in-depth knowledge on CSS Variables, definitely check out the MDN spec for them. I’ve also added this feature to my website recently, so you can check it out in the navigation! The first thing to do is to style our checkbox for which we used switch class on label tag. You can check out the fully working demo right here: :root Īnd there we go! A fully functioning light/dark mode using CSS Variables, some basic JavaScript and localStorage. Actually, it’s exactly the same as if we had used html in place of :root (except it has higher specificity). We can add these to the :root pseudo class. Starting, we’ll add the CSS Variables for our default/light mode. Inherits dark mode from the OS when enabled, and allows switching in-browser. They are set using custom property notation (e.g., - main-color: black ) and are accessed using the var() function (e.g., color: var( - main-color) ) If you want to read more about CSS Variables, you can check it out over here.ĬSS Variables (or CSS Custom Properties) are entities defined by CSS authors that contain specific values to be reused throughout a document. I recently wrote an article that goes in-depth on what they exactly are and what some do’s and don’t are. We will be using CSS Custom Properties, better known as CSS Variables, which we can reference and modify in our CSS file. Dark mode has become popular in the last 35 years as companies began to roll out these modes to make night users and those with bright screens benefit. If you don’t have a website of your own to which you wish to add this functionality, use this demo website to follow along. In the example below, emulating a simple website landing page, dark mode is enabled with prefers-color-scheme media query in JavaScript and can be overridden with a mode switch. These are the steps we will be following: So to follow along with this article you can open up your own text editor, but I also created a couple of Sandboxes for you to follow along without having to touch any code yourself. In this article, I’ll guide you through how to create your very own using CSS Variables, some basic JavaScript, and the use of localStorage! Follow along Giving your users a way to customise their experience on your website is a huge win for user experience. Either you use it as when and wherever you can, or you don’t use it at all. A toggle (or a switch) is a component which allows you to change a state / a boolean value from true to false and vice-versa.#Dark mode switch examples code#
#Dark mode switch examples how to#