Dark Mode on website using CSS and JavaScript

How to do an alternative color switch between dark and light theme on your website

by Tibor Kopca Date: 10-11-2020 javascript webdev code programming css dark theme

In today’s article we are going to learn how to build pretty much standard these days on the web pages and that is the alternative color mode and switching between them. This is very useful when during night you want the user to be able to NOT suffer by staring at very bright colors, and vice versa during the day it's better not having colors so dark on your page.

Continue reading to discover how to easily make a switchable dark theme for your page and how to implement a button for it.

Why Dark Mode?

Alternative mode to display web apps or ordinary sites is getting a lot of attention in recent years. Browsers have it, Google, Youtube offers dark mode, Apple added it to its iOS, even Windows has done the same in version 10.

The dark mode is mainly used as a supplemental mode to a light theme. It allows to lessen the strain on your eyes and normally it should be easy to switch on and off.

Using JavaScript and CSS

So the first thing we need is a web page where we want to add the Dark Mode. Let's open HTML code in a code editor like Visual Studio Code, or some other you like. The first thing to do is to find the place where we want to put the icon or button to activate or deactivate the mode.

Now here we have our header and behind ‘Login’ and ‘Register’ links we will place our button, with id so we can build the functionality with JavaScript and class to be able to manipulate its style with CSS. Inside the code for the button we will place two icons, and we're going to be using FontAwesome - the icon source, where you can find most of the icons you desire.

The icons would be placed into etiquette <span> , but first we need to link the file with icons. On our page, in the head etiquette we had already downloaded FontAwesome4 and linked to it like we can see here.

<link rel="stylesheet" href="css/font-awesome.min.css"> <!-- FontAwesome 4-->

The code for the menu:

<nav class="menu">
    <a href="#about">About</a>              <!--ES> Acerca de-->
    <a href="#work">My work</a>             <!--ES> Trabajos-->
    <a href="#contact">Contact</a>          <!--ES> Contacto-->
    <button class="darkModeSwitch" id="switch">Dark mode switch
      <span><i class="fa fa-sun-o"></i></span>   
      <span><i class="fa fa-moon-o"></i></span>


If you like to use new-ish FontAwesome 5 icons, you need to have an account.


There are two ways to implement custom icons, by downloading and linking .css sheet or linking the styles to the internet. The latter we use here, we go to the FontAwesome, select ‘Start a new project with a kit’, select ‘Your Kits’, choose your kit, likely named weirdly with numbers and letters, and from there you click on the name, click on button ‘Copy Kit Code’ and that paste into your HTML code into etiquette head.

<script src="https://kit.fontawesome.com/f09689b89n.js" crossorigin="anonymous"></script> <!--FontAwesome 5-->

Now you can happily use the icons in your HTML code. So we find icons we like, and copy the icon HTML code.


Now change the icon names or paste a HTML code previously copied according to the version of icons. Later we can easily change the style of the icons with CSS, like color and size to transform it into whatever you’d like.

<span><i class="fas fa-sun"></i></span>
<span><i class="fas fa-moon"></i></span>

We give it a style right away in a .css file. Cursor we want to be a pointer, that's when you hold the mouse over it, it will look like a mini hand and the rest like this. Position will be relative for having another element sitting on this.

    background: #3494b1;
    position: relative;
    cursor: pointer;
    outline: none;
    border: none;
    border-radius: 1rem;
    align-items: center;
    justify-content: space-between;

With this done, we want to change the style of the icons, so they are inside <span>

.darkModeSwitch span{
    background: none;

So far we have something like this:


Now we have to do a small circle which will hide one or another option. We use the pseudoselector ‘After’, which will add anything behind the selector class. With property absolute we can play with the position of the circle in the box we made earlier - in which it is located(.darkModeSwitch) - by telling its position should be top,left,right: X px, we can define its starting position in the element. Top:0 and Left:0 would set the starting point or coordinate of the button to be top and left. If we set right:0 and left:unset, the button’s position would be on the right side. Later we will make it move left and right by alternating the position of the button. Then, content must be empty so that the other styles could work. Notice the transition, with this set to 0.5s the change of the colors won't be so drastic and sudden.

    background: #fffbf5;
    width: 2.4rem;
    height: 2.4rem;
    position: absolute;
    border-radius: 3rem;
    transition: all .5s ease;
    box-shadow: 0 0 2px 2px rgba(0, 0, 0, .5);
    content: "";


So with this we have the visual part done. Now we want also the button to change the color of its background so the light mode would be more visible when the screen is very dark. When for example this button would have another class, let's call it ‘active’ to express the state of it, the button will change colors. And furthermore, when this will happen, also we change the attributes of the pseudoelement ‘after’ so it will be on the right side by overwriting values ‘left’ to unset and ‘right’ to value 0. This functionality we’d do like this:

  background: #fdd384;


Toggling Themes - JavaScript Part

So the rest of the work will be to actually add the class ‘active’ when we click on the button. This we’d achieve with JavaScript. Navigate yourself into the javascript file, if you don't have one, create and link it with this line in the index.html, for example right before closing etiquette of the body.

    <script src="js/main.js"></script>

In the JS file we put this code which will do this: We would manipulate the element called ‘switch’(remember that one in HTML code) and on the element we place the event listener - the method which expects 2 parameters. First is on what type of event should be executing the code. Second is what code should be running. This will be a function that adds or removes class with attribute ‘dark’ on the HTML element ‘body’. See the inspector in the browser and watch the body obtains our dark class upon the button is clicked. This way we would make a toggle between two states, one that has the class ‘dark’ and the one that hasn't. Also we want to do when the button is clicked, the ‘active’ class would be added to the button and by this we change the appearance of the button itself.

const switchButton = document.getElementById('switch');
switchButton.addEventListener('click', () => {
    document.body.classList.toggle('dark'); //toggle the HTML body the class 'dark'
    switchButton.classList.toggle('active');//toggle the HTML button with the id='switch' with the class 'active'


Hello dark mode my old friend

Now we want to actually have some different color to our page. As we have set in the CSS code here, background color is set to white-ish. Now add an alternate color you pick to the class ‘dark’ of the body.

body {
  background: #f2f2f2;
  font-family: "Lato", Helvetica, sans-serif;
  background:  #5436;



As you could see, it's fairly easy to create a website with HTML, CSS and a bit of JavaScript which has two color modes. The problem we could be facing is that with every load of the page, that is even if you hit F5 to refresh the page or you have a multi page site, the code which will be loaded will be the same every time. The result will be the user will always see the light mode at every load of the page.

What is missing to this code is some memory to the settings we choose. If we have for example implemented code for storing information like cookies or session storage, the user data would be stored in the client’s browser and at the next visit of your page it would be recognized which settings the user had and the correct display mode would be loaded. We wrote how to set up cookies last month, here is the link to our article about cookies. In the next article we will explain how to complete the dark mode with storing the user's preferences to address this problem.


Hopefully this article showed you a few tips you can use when you’re designing a website or web app. We explained how to create CSS code for the alternative theme and by the switching of a button it would give a totally different feel to your site. And with the benefit of more comfort for the user and that is what we all desire.

Image base from Unsplash

by Tibor Kopca Date: 10-11-2020 javascript webdev code programming css dark theme hits : 9055  
Tibor Kopca

Tibor Kopca

From tinkering with computers as a teenager, through a career in datacenter he stepped into web development with full force and started coding. Absorbs all information like a sponge.
Fan of aerospace, engineering, information technologies and watches.


Related Posts

Difference between arrow and normal functions in JavaScript

In this tutorial we are going to see how arrow functions differ from normal JavaScript functions. We will also see when you should use one and when you should use…

JavaScript Arrow functions: What they are and how to use them

In this article we are going to see what they are and how to use JavaScript Arrow Functions, a new feature introduced with the ES6 standard (ECMAScript 6). What are Arrow…

How to insert an element into an array with JavaScript

In this brief tutorial you will learn how to insert one or more elements into an array with JavaScript. For this we will use the splice function. The splice function will not…

What is the difference between primitives types and objects in JavaScript?

In this short tutorial we are going to look at the differences between primitive types and objects in JavaScript. To start with, we're going to look at what primitive types…

How to get DOM elements with JavaScript

When you access any element of the DOM, it is usual to save it in a variable. This is something that at first might seem very simple, but if you…

How to reverse an array in JavaScript

In this tutorial we are going to see how you can change the order of the elements of an array so that they are inverted. You could use a loop…

How synchronize the scroll of two divs with JavaScript

In case you have two divs of different sizes you may sometimes want to scroll both at the same time but at different speeds depending on their size. For example,…

Nesting: future proofing CSS

Although not currently supported by browsers, there is a proposal for CSS nesting to support a feature that would provide better readability to native CSS, so in the future it…

How to use the codePointAt method in JavaScript

The JavaScript codePointAt method has more or less the same function as the charCodeAt method, used to get the 16-bit Unicode representation of the character at a certain position in…

How to check if a value is a number in JavaScript

In this short tutorial we are going to look at the various methods that exist to find out if a value is a number in JavaScript.   1. Using the isNaN() function   One…

How to use the charCodeAt method in JavaScript

The charCodeAt method is accepted by strings in JavaScript, returning the 16-bit Unicode code of the character at the position we pass as a parameter to the method. The charCodeAt method…

How to use the charAt method in JavaScript

The charAt method is accepted by strings in JavaScript, returning the position of the character passed as a parameter within the string. If the string contains multiple occurrences of the character…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration