全书目录

第三十五篇:Astro 完全指南 —— 内容展馆群岛宇宙

第二十二章:图片和样式,在 Astro 里不是小事,而是内容展馆体验的核心

1 分钟 234 字 第 674 / 962 个阅读单元

内容型网站里,图片和排版不是边角料,是主舞台。

Astro 在这件事上的思路很实用。

#1. 图片优化
astro
---
import { Image } from 'astro:assets';
import cover from '../assets/museum-cover.jpg';
---

<Image
  src={cover}
  alt="内容展馆主视觉"
  widths={[480, 960, 1440]}
  sizes="(max-width: 768px) 100vw, 960px"
/>

这背后的心智:

  • 放在 src/ 的本地图片,Astro 可以参与优化
  • public/ 里的资源只是原样发出去
  • 远程图片需要在配置里允许域名或模式
#2. 样式默认局部作用域

Astro 的 <style> 默认 scoped,这很适合组件化展馆。

astro
<style>
  h2 {
    color: #173c3f;
  }
</style>

如果你真的要全局样式,再显式写:

astro
<style is:global>
  :root {
    --hall-bg: #fffdf7;
  }
</style>

所以 Astro 在样式上的态度也是:

text
默认局部安全
需要全局时再明确放开

这比内容站里“全局 CSS 到处串味”健康得多。