DEV Community

Emerald RLM
Emerald RLM

Posted on

1 1

The Right Way for Web Apps Theming. Dark-mode, light-mode, system and many more.

Recently I experimented with creating themes for my web apps and found many ways to create themes but there was conflict in the execution due to over-rides, so I will run with you through how I solved the issue.

So we will cover:

  1. How to create themes.
  2. The conflict between theming methods.
  3. Resolving the conflict.

How to create themes

There are three ways to create themes
1.Using css variables: Using both CSS and JavaScript, you define the variables in a parent element and using JavaScript call a function that changes the variable values, it can be reverted by calling a function that does the opposite of the previous function.
2.Using additional classes: Using JavaScript and CSS, you get the parent element and add a class containing the values you want to change and it can also be reverted using another function by removing the class.
3.Using media queries: Using CSS

@media (prefers-color-scheme: dark )
Enter fullscreen mode Exit fullscreen mode


, you can check mozzila documents to learn more, but what it does is update the elements styles according to the user's operating systems theme;

The Theme Conflict

I was learning to use styled-components with next.js so I had both the media queries theme and was using the theme provider to update the theme, I was going for my user's having three themes to choose from i.e light, dark and system but when the user's system was in dark-mode the media query theme clashed with my themes from the theme provider.

Resolving the Conflict:

I had to create a new .css file with a .dark class containing the styles I wanted to apply, so whether in dark-mode or light mode the class added takes precedence over
the other theming methods,
To summarize the order of precedence of theming methods is :

  1. Class method
  2. Media query method
  3. Themes from theme provider (using styled-components)

Extra:

Remember to save your client's last theme to the local storage or something to prevent bad UX and achieve consistent theme even on reloads.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay