在网页开发中,动态修改主题颜色是提升用户个性化体验的常用功能,借助css变量可以高效实现这个需求,无需逐个调整大量样式规则。css变量又称自定义属性,允许开发者在样式表中定义可复用的值,后续修改时只需要更新变量值就能同步所有引用该变量的样式。

css变量的基本定义与使用
css变量需要以两个减号开头作为属性名,通常定义在根伪类:root中,这样可以在整个文档范围内被访问。定义后的变量可以通过var()函数来引用,下面是基础的定义和使用示例。
/* 在根元素定义主题相关变量 */
:root {
--primary-color: #409eff; /* 主色调 */
--bg-color: #ffffff; /* 背景色 */
--text-color: #333333; /* 文字颜色 */
}
/* 引用变量应用到样式 */
.header {
background-color: var(--primary-color);
color: #ffffff;
}
.page-content {
background-color: var(--bg-color);
color: var(--text-color);
}
通过JavaScript动态修改css变量
css变量定义在根元素上后,可以通过JavaScript的setProperty方法动态修改其值,所有引用该变量的样式会自动更新,从而实现主题切换的效果。下面是具体的实现步骤和代码。
1. 准备主题切换的按钮
首先在页面中添加切换主题的按钮,用于触发变量修改的逻辑。
<div class="theme-switcher"> <button class="theme-btn" data-theme="light">浅色主题</button> <button class="theme-btn" data-theme="dark">深色主题</button> </div>
2. 编写主题切换的逻辑
通过监听按钮的点击事件,获取对应的主题配置,然后修改根元素上的css变量值。
// 定义不同主题的变量配置
const themeConfig = {
light: {
'primary-color': '#409eff',
'bg-color': '#ffffff',
'text-color': '#333333'
},
dark: {
'primary-color': '#6c8cff',
'bg-color': '#1a1a1a',
'text-color': '#e5e5e5'
}
};
// 获取所有主题切换按钮
const themeBtns = document.querySelectorAll('.theme-btn');
// 绑定点击事件
themeBtns.forEach(btn => {
btn.addEventListener('click', () => {
const theme = btn.dataset.theme;
const config = themeConfig[theme];
// 获取根元素
const root = document.documentElement;
// 遍历配置修改对应的css变量
for (const key in config) {
root.style.setProperty(`--${key}`, config[key]);
}
// 可选:将当前主题存储到本地,刷新后保持主题
localStorage.setItem('currentTheme', theme);
});
});
// 页面加载时读取存储的主题
window.addEventListener('DOMContentLoaded', () => {
const savedTheme = localStorage.getItem('currentTheme') || 'light';
const config = themeConfig[savedTheme];
const root = document.documentElement;
for (const key in config) {
root.style.setProperty(`--${key}`, config[key]);
}
});
注意事项
- css变量名区分大小写,定义和引用时需要保持名称一致。
- 如果变量值包含特殊字符,需要用引号包裹,比如
--bg-image: url("bg.png");。 - 修改css变量时,
setProperty的第一个参数是变量名,需要包含开头的双减号。 - 可以将主题配置存储在独立的对象中,方便后续扩展更多主题。
完整示例效果
将上面的样式、结构和逻辑组合后,点击不同按钮就能实时切换整个页面的主题颜色,所有引用了对应变量的元素样式都会同步更新,不需要额外编写大量样式替换代码。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS变量主题切换示例</title>
<style>
:root {
--primary-color: #409eff;
--bg-color: #ffffff;
--text-color: #333333;
}
body {
margin: 0;
background-color: var(--bg-color);
color: var(--text-color);
font-family: sans-serif;
transition: background-color 0.3s, color 0.3s;
}
.header {
background-color: var(--primary-color);
color: #ffffff;
padding: 20px;
text-align: center;
}
.content {
padding: 20px;
}
.theme-switcher {
margin-top: 20px;
}
.theme-btn {
padding: 8px 16px;
margin-right: 10px;
border: none;
border-radius: 4px;
cursor: pointer;
background-color: var(--primary-color);
color: #ffffff;
}
</style>
</head>
<body>
<div class="header">
<h1>CSS变量主题切换演示</h1>
</div>
<div class="content">
<p>这是一段示例文字,用于展示主题切换后的文字颜色变化。</p>
<div class="theme-switcher">
<button class="theme-btn" data-theme="light">浅色主题</button>
<button class="theme-btn" data-theme="dark">深色主题</button>
</div>
</div>
<script>
const themeConfig = {
light: {
'primary-color': '#409eff',
'bg-color': '#ffffff',
'text-color': '#333333'
},
dark: {
'primary-color': '#6c8cff',
'bg-color': '#1a1a1a',
'text-color': '#e5e5e5'
}
};
const themeBtns = document.querySelectorAll('.theme-btn');
themeBtns.forEach(btn => {
btn.addEventListener('click', () => {
const theme = btn.dataset.theme;
const config = themeConfig[theme];
const root = document.documentElement;
for (const key in config) {
root.style.setProperty(`--${key}`, config[key]);
}
localStorage.setItem('currentTheme', theme);
});
});
window.addEventListener('DOMContentLoaded', () => {
const savedTheme = localStorage.getItem('currentTheme') || 'light';
const config = themeConfig[savedTheme];
const root = document.documentElement;
for (const key in config) {
root.style.setProperty(`--${key}`, config[key]);
}
});
</script>
</body>
</html>
CSS变量css_variable主题切换前端样式修改时间:2026-07-18 12:30:29