如何修改Docusaurus中明暗模式切换按钮的图标?
替换Docusaurus明暗模式切换按钮为简洁太阳/月亮图标
核心思路:通过自定义CSS覆盖默认表情样式
Docusaurus的明暗切换按钮默认使用表情符号,我们可以通过CSS隐藏默认内容,替换为自定义的简洁图标。
方法一:纯CSS绘制图标
- 打开项目中的
src/css/custom.css文件(如果没有则新建该文件,Docusaurus会自动加载) - 添加以下CSS代码:
/* 隐藏默认的表情图标 */ .theme-toggle svg { display: none; } /* 亮模式下的切换按钮(显示太阳图标) */ .theme-toggle--light::before { content: ''; display: inline-block; width: 18px; height: 18px; border-radius: 50%; background: #fdb813; box-shadow: 0 0 0 2px #fdb813, 0 0 0 6px rgba(253, 184, 19, 0.1); } /* 暗模式下的切换按钮(显示月亮图标) */ .theme-toggle--dark::before { content: ''; display: inline-block; width: 18px; height: 18px; border-radius: 50%; border: 2px solid #fff; position: relative; } .theme-toggle--dark::after { content: ''; position: absolute; top: -4px; right: -4px; width: 16px; height: 16px; border-radius: 50%; background: #1a1a1a; /* 可替换为你的暗模式背景色 */ }
方法二:使用SVG图标(更精致)
如果需要更细腻的图标,用SVG作为背景替换:
/* 隐藏默认表情 */ .theme-toggle svg { display: none; } /* 太阳图标(亮模式切换按钮) */ .theme-toggle--light::before { content: ''; display: inline-block; width: 20px; height: 20px; background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>'); background-size: contain; background-repeat: no-repeat; } /* 月亮图标(暗模式切换按钮) */ .theme-toggle--dark::before { content: ''; display: inline-block; width: 20px; height: 20px; background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>'); background-size: contain; background-repeat: no-repeat; }
注意事项
- 如果类名不匹配:打开浏览器开发者工具,定位切换按钮元素,查看实际类名(比如部分版本可能是
.navbar__toggle .theme-toggle),调整CSS选择器即可。 - 颜色适配:可以根据站点的主题色调整图标颜色、背景色等参数。
内容的提问来源于stack exchange,提问作者PudgyPigeon
相关产品推荐
相关产品推荐

