Adding Dark / Light Theme To The Website Using Only CSS

Bipin Rajbhar - Apr 25 '20 - - Dev Community

Hello everyone ๐Ÿ‘‹, I hope you are doing great.

So, Today you are going to learn how to Add dark/light theme to your website using only CSS ๐Ÿ˜Ž.

HTML

Let's first set up our HTML.

<input id="toggle-theme" class="toggle-theme" type="checkbox" checked/>

<main >
  <label for="toggle-theme" class="toggle-theme-label">
    <span>๐Ÿ’ก</span>
</label>
  <article>
  <header>Dark / Light Mode Using Only CSS</header>
  <p>...</p>
</article>
</main>
Enter fullscreen mode Exit fullscreen mode

CSS

Now lets set the background-colour and text colour of our HTML using CSS variables.


:root {
   --bg-color: #edf2f4;
   --text-color: #011627;
}

main {
  padding: 24px;
  background-color: var(--bg-color);
  color: var(--text-color);
}
Enter fullscreen mode Exit fullscreen mode

Now, lets set up the checkbox functionality when the checkbox is checked.

/* all the magic happing here โœจ*/
input[type="checkbox"]:checked ~ main {
  --bg-color: #011627;
  --text-color: #edf2f4;
}
Enter fullscreen mode Exit fullscreen mode

That's It ๐Ÿ˜Ž.

Example

๐Ÿ“š Further Reading:

Thanks for reading! My name is Bipin Rajbhar; I love helping people to learn new skills ๐Ÿ˜Š. You can follow me on Twitter if youโ€™d like to be notified about new articles and resources.

. . . . . . . . . . . . . . . . . . . . . . . . .