[CSS] Use CSS Variables with Calc and HSL to Implement Dark Mode

In this lesson, we use CSS variables with calc and hsl to implement a rudimentary dark mode.

We can do this by adjusting the lightness of our colors based on a binary value and some basic arithmetic.+

 

复制代码
:root {
  --dark: 1;
  --bg: hsl(190, 50%, calc((80 - (var(--dark, 0) * 60)) * 1%));
  --color: hsl(190, 20%, calc((30 + (var(--dark, 0) * 30)) * 1%));
}

body {
  min-height: 100vh;
  background: var(--bg);
  color: var(--color);
  font-family: sans-serif;
  font-size: 2.5rem;
  transition: background 0.2s, color 0.2s;
}

h1 {
  position: absolute;
  bottom: 1.25rem;
  right: 1.25rem;
  margin: 0;
  user-select: none;
}
复制代码
document.addEventListener("click", () => {
  document.documentElement.style.setProperty(
    "--dark",
    document.documentElement.style.getPropertyValue("--dark") === "1" ? 0 : 1
  );
});

 

posted @   Zhentiw  阅读(109)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2018-11-02 [MDX] Build a Custom Provider Component for MDX Deck
2018-11-02 [WASM + Rust] Debug a WebAssembly Module Written in Rust using console.log
2017-11-02 [AngularFire] Firebase OAuth Login With Custom Firestore User Data
2017-11-02 [AngularFire2 & Firestore] Example for collection and doc
2015-11-02 [Ruby] LEVEL 2 Methods and Classes
2015-11-02 [Rails Level 2] Ground up
2015-11-02 [AngularJS] 5 simple ways to speed up your AngularJS application
点击右上角即可分享
微信分享提示