使用 Tailwind Typography 设置渲染后的 Markdown 样式
你可以使用 Tailwind 的 Typography 插件来为来自 Astro 内容集合 等源的 Markdown 内容渲染样式。
本指南将教你如何创建一个可复用的 Astro 组件,用以使用 Tailwind 的功能类来为你的 Markdown 内容添加样式。
先决条件
标题为“先决条件”的部分一个 Astro 项目,并且:
- 已安装 Tailwind 的 Vite 插件。
- 使用了 Astro 的内容集合。
设置 @tailwindcss/typography
标题为“设置 @tailwindcss/typography”的部分首先,使用你偏好的包管理器安装 @tailwindcss/typography
。
npm install -D @tailwindcss/typography
pnpm add -D @tailwindcss/typography
yarn add --dev @tailwindcss/typography
然后,在你的 Tailwind 配置文件中将该包添加为插件。
@import 'tailwindcss';@plugin '@tailwindcss/typography';
-
创建一个
<Prose />
组件,它提供一个带有<slot />
的<div>
包装器,用于包裹你渲染后的 Markdown。在父元素中,添加prose
样式类以及任何所需的Tailwind 元素修饰符。src/components/Prose.astro ------<divclass="prose dark:prose-invertprose-h1:font-bold prose-h1:text-xlprose-a:text-blue-600 prose-p:text-justify prose-img:rounded-xlprose-headings:underline"><slot /></div>@tailwindcss/typography
插件使用元素修饰符来为带有prose
类的容器的子组件设置样式。这些修饰符遵循以下通用语法
prose-[element]:class-to-apply例如,
prose-h1:font-bold
会为所有的<h1>
标签赋予font-bold
Tailwind 类。 -
在你想要渲染 Markdown 的页面上,查询你的集合条目。将
await render(entry)
中的<Content />
组件作为子组件传递给<Prose />
,从而用 Tailwind 样式包裹你的 Markdown 内容。src/pages/index.astro ---import Prose from '../components/Prose.astro';import Layout from '../layouts/Layout.astro';import { getEntry, render } from 'astro:content';const entry = await getEntry('collection', 'entry');const { Content } = await render(entry);---<Layout><Prose><Content /></Prose></Layout>