

Thanks to this implementation, we can choose to style elements differently based on which class name the HTMLĮlement has. With this, we’ve implemented everything we need to switch between a light and dark theme! 2. Here’s what happens to our HTML element depending on the button clicked:Īnd the style for the body tag looks like this: We can pass this function to our buttons so the updated HTML looks like this: Ĭlicking the light button sets the HTML class to light and clicking the dark button sets the HTML The setTheme function sets the root element’s class to the parameter theme. Only need one line: const setTheme = theme => = theme The body tag returns the selected variable color depending on the class assigned to the :root.Īt this point we can use JavaScript to determine the class for the :root tag and, as promised, we’ll We can assign colors to the body like this: In the first place, make a HTML document with the name of index.html and glue the given codes in your HTML record. After creating these files just paste the following codes in your file. First, you need to create two Files one HTML File and another one is CSS File. Now we’ll assign our custom properties to other elements–this is what allows the colors to change depending on the To create this program (Dark Mode Switch). (e.g., color: var(-main-color) )” - MDNĬustom properties are usually defined inside the :root pseudo-class, which allows us to target the Įlement tag. In this example, we defined the variables for a default, light and dark theme for the They are set usingĬustom property notation (e.g., -main-color: black ) and are accessed using “Custom properties contain specific values to be reused throughout a document. We define our theme colors using CSS custom We can style the buttons to achieve the rounded Most of the work with our toggle implementation is done using CSS. I also set the title attribute to provide context for screen readers. Įlements for the sun and moon to represent light and dark themes, but you can replace them with whateverĬontent you prefer.
#HTML DARK MODE SWITCH HOW TO#
How to Create a Dark Mode Toggle HTMLįirst, we’ll initialise two buttons to allow us control light and dark mode. We’ll be building this first, then expanding on Let’s take a look at the demo for a light/dark mode toggle switch. Remember which of our color schemes they’ve selected. We’ll also use media queries to display dark or light mode depending on a user’s preferences, and local storage to Themes as we’d like light mode, dark mode, 90’s neon mode, you name it!

Then we’ll expand on that to implement as many First, we’ll implement a simple light/dark mode toggle switch.
