✨Kevin‘s Blog🪐

Astro 博客实现夜间模式全攻略

📅发布日期:7/13/2025

现代博客已经离不开“夜间模式”这一项体验优化,尤其对于喜欢深夜写作或阅读的开发者和极客来说,能一键切换亮 / 暗色主题,不仅护眼,也很酷。

今天这篇文章就手把手带你给 Astro 博客加上完整的夜间模式功能,包括:


🧱 第一步:设置颜色变量

我们在 src/styles/global.css 中定义主题色变量。

:root {
  --bg: #ffffff;
  --fg: #1e1e1e;
  --font-body: 'Inter', 'Noto Sans SC', sans-serif;
  --font-size: 17px;
  --line-height: 1.75;
  --max-width: 720px;
}

:root[data-theme="dark"] {
  --bg: #1e1e1e;
  --fg: #ffffff;
}

body {
  background-color: var(--bg);
  color: var(--fg);
  font-family: var(--font-body);
  font-size: var(--font-size);
  line-height: var(--line-height);
  max-width: var(--max-width);
  margin: 0 auto;
  padding: 2rem 1rem;
  transition: background-color 0.3s ease, color 0.3s ease;
}

🎨 第二步:适配代码块暗色样式

pre {
  background-color: #f5f5f5;
  padding: 1em;
  border-radius: 8px;
  overflow: auto;
}

code {
  background-color: #f0f0f0;
  padding: 0.2em 0.4em;
  border-radius: 4px;
  font-family: Menlo, monospace;
}

:root[data-theme="dark"] pre {
  background-color: #2d2d2d;
  color: #f8f8f2;
}

:root[data-theme="dark"] code {
  background-color: #3a3a3a;
  color: #f8f8f2;
}

🧩 第三步:创建主题切换按钮组件

src/components/ThemeToggle.astro 中新建如下组件:

---
const htmlId = "theme-toggle";
---

<button id={htmlId} aria-label="切换夜间模式">🌙</button>

<script>
  const html = document.documentElement;
  const toggleButton = document.getElementById("theme-toggle");

  const savedTheme = localStorage.getItem("theme");
  const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
  const currentTheme = savedTheme || (prefersDark ? "dark" : "light");
  html.setAttribute("data-theme", currentTheme);

  const updateIcon = () => {
    const isDark = html.getAttribute("data-theme") === "dark";
    toggleButton.textContent = isDark ? "🔆" : "🌙";
  };

  updateIcon();

  toggleButton?.addEventListener("click", () => {
    const isDark = html.getAttribute("data-theme") === "dark";
    const newTheme = isDark ? "light" : "dark";
    html.setAttribute("data-theme", newTheme);
    localStorage.setItem("theme", newTheme);
    updateIcon();
  });
</script>

🧱 第四步:在布局中引入组件

打开你的 src/layouts/Layout.astro 文件,在 <header> 中插入该组件:

---
import ThemeToggle from "../components/ThemeToggle.astro";
---

<header>
  <h1>✨我的数字游乐场🪐</h1>
  <nav>
    <a href="/">主页</a> | <a href="/blog">博客</a>
  </nav>
  <ThemeToggle />
</header>

🧼 第五步:美化按钮样式

继续编辑 global.css,为按钮设置样式:

button#theme-toggle {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 1.2rem;
  margin-left: 1rem;
}

✅ 效果展示


🧠 技术原理小结


🎉 现在你的 Astro 博客也支持了真正实用的夜间模式,下一节我们将实现中英语言切换和封面摘要卡片布局,敬请期待!


📦 PNG 压缩与 WebP 转换在线工具推荐

以下是几个支持 PNG 压缩和 WebP 转换的免费在线工具:

使用方法:上传 PNG 图片,选择 WebP 格式并压缩,下载即可用于博客封面或文章插图。


🖥️ 4K 背景屏幕常用分辨率

4K 屏幕的标准分辨率为 3840 × 2160 像素(宽 × 高),也称为 UHD(Ultra HD)。设计用于 4K 显示器的背景图片建议尺寸:

建议图片尺寸不低于上述分辨率,以保证在 4K 屏幕下显示清晰无锯齿。