0

Suppose I have 2 stylesheets, dark.css and light.css . I want to allow the user to switch between these two themes in the homepage and set it as default to other pages too. My website also contains many other css files which are almost same for both themes( otherwise it would be a problem!!)

1

1 Answer 1

0

We should never switch or unload css file in order to do such things. It is better to switch a class in html or body element.

For example - First of all load both css style file. Then for dark.css, wrap all your styles under root class dark just like below -

.dark .style1{ ... } .dark .style2{ ... } 

Same for light.css

.light .style1{ ... } .light .style2{ ... } 

And then switch the class of body tag using below JavaScript -

<button id="dark">Dark theme</button> <button id="light">Light theme</button> 
let body = document.body; let darkBtn = document.getElementById('dark'); let lightBtn = document.getElementById('light'); darkBtn.addEventListener('click', () => { body.classList.remove('light'); body.classList.add('dark'); }); lightBtn.addEventListener('click', () => { body.classList.remove('dark'); body.classList.add('light'); }); 

Live in action - https://jsitor.com/3xKxgP8Ow

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.