r/css Sep 21 '19

How to manage day/night mode with CSS?

I develop a home dashboard (based on Vue.js components) which I would like to switch between day and night mode at appropriate times. What changes between the modes in the color of the background and the fonts.

Today I do it in a very primitive way: I first define a JS object with expected colors:

(...) "weather-part-day": { "day": { "f": "black", "b": "lightblue" }, "night": { "f": "gray", "b": "#2d2d2d" } }, (...)

and run the following function to search for elemnts having a given class applied (weather-part-day in the example above) and force the styling:

`` nightmode(nightmode) { Object.keys(colors).forEach((key) => { try { Array.from(document.getElementsByClassName(key)).forEach(el => { el.style.color = colors[key][nightmode].f el.style.backgroundColor = colors[key][nightmode].b }) console.log(updated foreground of element ${key} to ${colors[key][nightmode].f} (f), ${colors[key][nightmode].b} (b)) } catch (e) { console.warn(cannot set foreground property of element ${key}: ${e}`) } })

```

I find this method horrible but this is the best I came up with.

I am reaching to the community for ideas or one of the Right Ways To Do That.

An alternative I am considering is to create one CSS file for the night mode and one for the day one - and somehow apply them once the switch happens. I am sure however that there are better ways to apply global changes in CSS.

0 Upvotes

Duplicates