[CSS] Easy dark or light mode
You only require a few lines of CSS to enable a dark/light mode on your website. You just need to let browsers know that your website can display correctly in system dark/light mode:
html {
color-scheme: light dark;
}
Note:
color-scheme
property can be set on any DOM element other thanhtml
.
Then set variables that control background color and text color through your website, making it even more bullet proof by checking for browser support:
html {
--bg-color: #ffffff;
--txt-color: #000000;
}
@supports (background-color: Canvas) and (color: CanvasText) {
:root {
--bg-color: Canvas;
--txt-color: CanvasText;
}
}
Note: If you don't set
background-color
on an element, it will inherit the browser-defined system color for the dark/light theme matched. These system colors can be different between different browsers.
Setting background-color
explicitly can be useful in combination with prefers-color-scheme
to give a different shade of color different from the default that the browser sets.
Below is the dark/light mode in action. User's preference is simulated between dark and light mode.
Other approach:
@media (prefers-color-scheme: dark) {
:root {
--bg-color: #333;
--txt-color: #f5f5f5;
}
}
@media (prefers-color-scheme: light) {
:root {
--bg-color: #f5f5f5;
--txt-color: #333;
}
}
body {
background-color: var(--bg-color);
color: var(--txt-color);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2021-07-20 [SAA + SAP] 06. Containers on AWS: ECS, Fargate, ECR & EKS
2020-07-20 [XState] Assignement actions
2020-07-20 [XState] Using global actions prop for testing
2018-07-20 [Vue @Component] Simplify Vue Components with vue-class-component
2017-07-20 [HTML] Change an HTML5 input's placeholder color with CSS
2017-07-20 [Node] Run Any Version of a Node Tool with npx
2016-07-20 [CSS] Make element not selectable