DEV Community

Cover image for Adding Dark / Light Theme To The Website Using Only CSS
Bipin Rajbhar
Bipin Rajbhar

Posted on • Edited on

39 9

Adding Dark / Light Theme To The Website Using Only CSS

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.

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

Top comments (5)

Collapse
 
cbartlett profile image
Colin Bartlett

I found an interesting tool to help with this the other day on ProductHunt: nighteye.app/dark-css-generator/

It worked pretty well! Not sure how maintainable it is to have a separate stylesheet. But I was very impressed with the results they created.

Collapse
 
ameedjamous profile image
Ameed Jamous

I wish all websites and docs had this light bulb :) Good stuff!

Collapse
 
adgower profile image
Alex Gower

Awesome

Collapse
 
obasekietinosa profile image
Etinosa Obaseki

🤯🤯🤯 Are there any drawbacks to using this as opposed to more involved solutions?

Collapse
 
bipinrajbhar profile image
Bipin Rajbhar

maybe or may not 🤔

If you have answer let me know in the comment 😄

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay