

Next we will add some CSS styling for the dark mode. Outline:none /* Not ideal for accessibility */īox-shadow: inset 1px 1px 3px 0 rgb(0 0 0 / 40%) īox-shadow: 1px 1px 2px 0 rgb(0 0 0 / 40%)

You can can include the CSS as an external css document (and link to it in the head), or simple place it inline in the head immediately before the closing head tag between like so: Next we will add some CSS styles for the button element. Var app = document.getElementsByTagName("BODY")
#Html dark mode switch code
Place this code immediately before the closing body tag: I find this method offers a bit more flexibility, particularly when using tools such Codepen where it is not straightforward to include an id or class on the body element. You could just refer to the body tag directly. I also use a particular method where I create a variable for the body tag which I call ‘app’. For more information on data attributes checkout this link. Please note: In this example I decided to use a custom data attribute that I named ‘light-mode’ however you could simply toggle css classes if you prefer.

I’ve also included another basic version that has a really small toggle button only in the top right of the window.
#Html dark mode switch download
If you simply want to download the code you could right click on the link and select to save the source code to your computer. Using HTML and CSS as much as possible to code dividers and separators will allow them to also switch colors to stay consistent with the design. You will see that your selection is stored and applied when the page loads. Click the button to toggle between dark and light mode for this page. Try clicking the toggle button and reloading the page. Switch between dark and light mode with CSS and JavaScript.
