search
HomeWeb Front-endCSS TutorialVue uses CSS variables to implement the theme switching function

Theme management can often be seen on websites. The general idea is to separate the theme-related CSS styles and load the corresponding CSS style files when the user selects the theme. Most browsers are now well compatible with CSS variables, and themed styles are easier to manage. Recently, I used CSS variables to do a theming practice in the Vue project. Let’s take a look at the whole process.

Vue uses CSS variables to implement the theme switching function

Github project address https://github.com/JofunLiang/vue-project-themable-demo

Demo address https://jofunliang.github .io/vue-project-themable-demo/

Feasibility test

In order to test the feasibility of the method, create a new themes folder under the public folder. And create a new default.css file in the themes folder:

:root {
  --color: red;
}

Recommended learning: CSS video tutorial

in Introduce external style theme.css into the index.html file of the public folder, as follows:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title>vue-skin-peeler-demo</title>
    <!-- 引入themes文件夹下的default.css -->
    <link rel="stylesheet" type="text/css" href="src/themes/default.css" rel="external nofollow">
  </head>
  <body>
    <noscript>
      <strong>We&#39;re sorry but vue-skin-peeler-demo doesn&#39;t work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

Then, use CSS variables in Home.vue:

<template>
  <div>
    <div :class="$style.demo">变红色</div>
  </div>
</template>
<script>
export default {
  name: &#39;home&#39;
}
</script>
<style module>
  .demo {
    color: var(--color);
  }
</style>

Then , run the project and open the page in the browser, the page displays normally.

Note: @vue/cli using the link tag to introduce css styles may report an error "We're sorry but vue-skin-peeler-demo doesn't work properly without JavaScript enabled. Please enable it to continue ." This is caused by @vue/cli packaging all files in the src directory through webpack. Therefore, static file resources must be placed in the public (if @vue/cli 2.x version is placed in static) folder.

Implementing theme switching

The idea of ​​​​theme switching here is to replace the href attribute of the link tag. Therefore, you need to write a replacement function in src Create a new themes.js file in the directory, the code is as follows:

// themes.js
const createLink = (() => {
  let $link = null
  return () => {
    if ($link) {
      return $link
    }
    $link = document.createElement(&#39;link&#39;)
    $link.rel = &#39;stylesheet&#39;
    $link.type = &#39;text/css&#39;
    document.querySelector(&#39;head&#39;).appendChild($link)
    return $link
  }
})()
/**
 * 主题切换函数
 * @param {string} theme - 主题名称, 默认default
 * @return {string} 主题名称
 */
const toggleTheme = (theme = &#39;default&#39;) => {
  const $link = createLink()
  $link.href = `./themes/${theme}.css`
  return theme
}
export default toggleTheme

Then, create default.css and dark.css under the themes file Two theme files. Create CSS variables to implement theming. To implement theme switching with CSS variables, please refer to another article. First Contact with CSS Variables

Compatibility

IE browser and some older browsers do not support CSS variables, therefore, Requires css-vars-ponyfill, a ponyfill that provides client-side support for CSS custom properties (also known as "CSS variables") in both older and modern browsers. Since you need to enable watch monitoring, you also need to install MutationObserver.js.

Installation:

npm install css-vars-ponyfill mutationobserver-shim --save

Then, introduce and use it in the themes.js file:

// themes.js
import &#39;mutationobserver-shim&#39;
import cssVars from &#39;css-vars-ponyfill&#39;
cssVars({
  watch: true
})
const createLink = (() => {
  let $link = null
  return () => {
    if ($link) {
      return $link
    }
    $link = document.createElement(&#39;link&#39;)
    $link.rel = &#39;stylesheet&#39;
    $link.type = &#39;text/css&#39;
    document.querySelector(&#39;head&#39;).appendChild($link)
    return $link
  }
})()
/**
 * 主题切换函数
 * @param {string} theme - 主题名称, 默认default
 * @return {string} 主题名称
 */
const toggleTheme = (theme = &#39;default&#39;) => {
  const $link = createLink()
  $link.href = `./themes/${theme}.css`
  return theme
}
export default toggleTheme

After turning on watch, click on IE 11 browser Toggling the theme switch doesn't work. Therefore, if you re-execute cssVars() every time you switch the theme, you still cannot switch the theme. The reason is that re-executing cssVars() after turning on watch is invalid. Finally, the only option is to turn off the watch and then turn it back on. The themes.js code for successfully switching the theme is as follows:

// themes.js
import &#39;mutationobserver-shim&#39;
import cssVars from &#39;css-vars-ponyfill&#39;
const createLink = (() => {
  let $link = null
  return () => {
    if ($link) {
      return $link
    }
    $link = document.createElement(&#39;link&#39;)
    $link.rel = &#39;stylesheet&#39;
    $link.type = &#39;text/css&#39;
    document.querySelector(&#39;head&#39;).appendChild($link)
    return $link
  }
})()
/**
 * 主题切换函数
 * @param {string} theme - 主题名称, 默认default
 * @return {string} 主题名称
 */
const toggleTheme = (theme = &#39;default&#39;) => {
  const $link = createLink()
  $link.href = `./themes/${theme}.css`
  cssVars({
    watch: false
  })
  setTimeout(function () {
    cssVars({
      watch: true
    })
  }, 0)
  return theme
}
export default toggleTheme

To view all codes, please go to the Github project address.

Remember the theme

To implement the function of remembering the theme, one is to save the theme to the server, and the other is to use the local storage theme. For convenience, the local storage method of theme is mainly used here, that is, localStorage is used to store the theme. For specific implementation, please visit the Github project address.

This article comes from the PHP Chinese website, CSS tutorial column, welcome to learn

The above is the detailed content of Vue uses CSS variables to implement the theme switching function. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
@keyframes vs CSS Transitions: What is the difference?@keyframes vs CSS Transitions: What is the difference?May 14, 2025 am 12:01 AM

@keyframesandCSSTransitionsdifferincomplexity:@keyframesallowsfordetailedanimationsequences,whileCSSTransitionshandlesimplestatechanges.UseCSSTransitionsforhovereffectslikebuttoncolorchanges,and@keyframesforintricateanimationslikerotatingspinners.

Using Pages CMS for Static Site Content ManagementUsing Pages CMS for Static Site Content ManagementMay 13, 2025 am 09:24 AM

I know, I know: there are a ton of content management system options available, and while I've tested several, none have really been the one, y'know? Weird pricing models, difficult customization, some even end up becoming a whole &

The Ultimate Guide to Linking CSS Files in HTMLThe Ultimate Guide to Linking CSS Files in HTMLMay 13, 2025 am 12:02 AM

Linking CSS files to HTML can be achieved by using elements in part of HTML. 1) Use tags to link local CSS files. 2) Multiple CSS files can be implemented by adding multiple tags. 3) External CSS files use absolute URL links, such as. 4) Ensure the correct use of file paths and CSS file loading order, and optimize performance can use CSS preprocessor to merge files.

CSS Flexbox vs Grid: a comprehensive reviewCSS Flexbox vs Grid: a comprehensive reviewMay 12, 2025 am 12:01 AM

Choosing Flexbox or Grid depends on the layout requirements: 1) Flexbox is suitable for one-dimensional layouts, such as navigation bar; 2) Grid is suitable for two-dimensional layouts, such as magazine layouts. The two can be used in the project to improve the layout effect.

How to Include CSS Files: Methods and Best PracticesHow to Include CSS Files: Methods and Best PracticesMay 11, 2025 am 12:02 AM

The best way to include CSS files is to use tags to introduce external CSS files in the HTML part. 1. Use tags to introduce external CSS files, such as. 2. For small adjustments, inline CSS can be used, but should be used with caution. 3. Large projects can use CSS preprocessors such as Sass or Less to import other CSS files through @import. 4. For performance, CSS files should be merged and CDN should be used, and compressed using tools such as CSSNano.

Flexbox vs Grid: should I learn them both?Flexbox vs Grid: should I learn them both?May 10, 2025 am 12:01 AM

Yes,youshouldlearnbothFlexboxandGrid.1)Flexboxisidealforone-dimensional,flexiblelayoutslikenavigationmenus.2)Gridexcelsintwo-dimensional,complexdesignssuchasmagazinelayouts.3)Combiningbothenhanceslayoutflexibilityandresponsiveness,allowingforstructur

Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)May 09, 2025 am 09:57 AM

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

CSS Animations: Is it hard to create them?CSS Animations: Is it hard to create them?May 09, 2025 am 12:03 AM

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.