如何用SCSS创建明暗模式调色板并实现网站主题切换功能
实现SCSS全站明暗模式切换的调色板方案
1. 重构主题调色板(纠正单个变量的错误思路)
别再只用单个$dark-color了,要按主题维度定义完整的颜色映射,把浅色/深色主题下的背景、文本、边框、强调色等统一归类:
// 用SCSS map存储不同主题的完整颜色集合 $themes: ( light: ( bg-primary: #ffffff, text-primary: #1a1a1a, text-secondary: #666666, border-color: #e0e0e0, accent-color: #2563eb ), dark: ( bg-primary: #121212, text-primary: #ffffff, text-secondary: #a0a0a0, border-color: #333333, accent-color: #3b82f6 ) );
2. 将SCSS变量转为动态CSS自定义属性
SCSS变量是编译时静态的,没法动态切换,所以要把主题map里的变量注入到全局CSS自定义属性中,通过给body加类实现主题切换:
// 遍历主题map,生成对应主题类的CSS变量 @each $theme-name, $theme-colors in $themes { .theme-#{$theme-name} { @each $color-name, $color-value in $theme-colors { --#{$color-name}: #{$color-value}; } } } // 默认加载浅色主题 body { @include apply-theme(light); } // 封装混合宏快速应用主题变量(可选) @mixin apply-theme($theme-name) { $theme-colors: map-get($themes, $theme-name); @each $color-name, $color-value in $theme-colors { --#{$color-name}: #{$color-value}; } }
3. 全站样式统一引用CSS变量
所有元素样式都用这些全局自定义属性,不用写死颜色:
// 页面基础样式 body { background-color: var(--bg-primary); color: var(--text-primary); transition: background-color 0.3s, color 0.3s; // 加过渡动画提升体验 } // 组件示例 .card { border: 1px solid var(--border-color); background-color: var(--bg-primary); } .btn-accent { background-color: var(--accent-color); color: #ffffff; } .text-secondary { color: var(--text-secondary); }
4. 用JS实现切换按钮逻辑
给切换按钮绑定点击事件,切换body上的主题类,同时保存用户选择到本地存储:
const themeToggleBtn = document.querySelector('#theme-toggle'); // 初始化:读取本地存储的主题(无则默认浅色) const savedTheme = localStorage.getItem('theme') || 'light'; document.body.classList.add(`theme-${savedTheme}`); themeToggleBtn.addEventListener('click', () => { const currentTheme = document.body.classList.contains('theme-dark') ? 'light' : 'dark'; // 更新主题类 document.body.classList.remove(`theme-${currentTheme === 'light' ? 'dark' : 'light'}`); document.body.classList.add(`theme-${currentTheme}`); // 保存到本地存储 localStorage.setItem('theme', currentTheme); });
核心要点总结
- 不能只用单个深色变量,要保证每个视觉属性(背景、文本等)都有对应主题的变量,才能实现全站同步切换
- 依赖CSS自定义属性实现动态样式切换,纯SCSS变量做不到运行时修改
- 加入过渡动画让切换更丝滑,本地存储保存用户选择避免刷新重置
内容的提问来源于stack exchange,提问作者Yasin Dehfuli
相关产品推荐
相关产品推荐

