Change styles based on dark or light mode

六月ゝ 毕业季﹏ 提交于 2020-05-24 03:29:29

问题


I want to have a dark and a light theme on my Vue app. I can create dark.scss file and change classes styles and use !important property to override styles defined in components. Or I can use props in my components and change className with v-if based on the theme. e.g. set class to className__light when theme is light otherwise set to className__dark. which one is better in all situations like performance or time needed to do it?


回答1:


Well i would not do it with classes. I would create CSS variables with either SCSS or you create CSS variables in :root

If you do it with the :root method then it should look something like this:

:root {
   --background: red;
}

Then you can access it in any component like this for example:

.class {
   background: var(--background); // the background will appear red
}

Now you can change the background color with just 1 CSS variables.

To change the variable with Javascript you just write following:

 root.style.setProperty('--background', "green");

The problem here is that it isnt supported in IE if you care about browser support. So you should create an fallback like this:

.class {
   background: red; //fallback
   background: var(--background); // the background will appear red
}


来源:https://stackoverflow.com/questions/61079443/change-styles-based-on-dark-or-light-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!