使用 Tailwind Typography 美化渲染后的 Markdown
你可以使用 Tailwind 的 Typography 插件来美化如 Astro 的 内容集合 等来源的渲染后的 Markdown。
本指南将教你如何使用 Tailwind 的实用类创建一个可复用的 Astro 组件,以便美化你的 Markdown 内容。
前提条件
一个 Astro 项目:
- 已经安装了 Tailwind 的 Vite 插件。
- 使用了 Astro 的 内容集合。
设置 @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 />组件,提供一个被<div>包裹并包含你的渲染 Markdown 的<slot />。在父元素中添加样式类prose,并在其中添加任何你想要的 Tailwind 元素修饰符。--- --- <div class="prose dark:prose-invert prose-h1:font-bold prose-h1:text-xl prose-a:text-blue-600 prose-p:text-justify prose-img:rounded-xl prose-headings:underline"> <slot /> </div>:::tip
@tailwindcss/typography插件使用 元素修饰符 来为带有prose类的容器的子组件应用样式。这些修饰符遵循以下通用语法:
prose-[element]:class-to-apply例如,
prose-h1:font-bold会给所有的<h1>标签添加font-bold的 Tailwind 类。:::在你想要渲染 Markdown 的页面上查询你的集合条目。将
await render(entry)的<Content />组件作为子组件传递给<Prose />,以便用 Tailwind 样式包裹你的 Markdown 内容。--- 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>