跳转到内容

使用 Tailwind Typography 设置渲染后的 Markdown 样式

你可以使用 Tailwind 的 Typography 插件来为来自 Astro 内容集合 等源的 Markdown 内容渲染样式。

本指南将教你如何创建一个可复用的 Astro 组件,用以使用 Tailwind 的功能类来为你的 Markdown 内容添加样式。

一个 Astro 项目,并且:

首先,使用你偏好的包管理器安装 @tailwindcss/typography

终端窗口
npm install -D @tailwindcss/typography

然后,在你的 Tailwind 配置文件中将该包添加为插件。

src/styles/global.css
@import 'tailwindcss';
@plugin '@tailwindcss/typography';
  1. 创建一个 <Prose /> 组件,它提供一个带有 <slot /><div> 包装器,用于包裹你渲染后的 Markdown。在父元素中,添加 prose 样式类以及任何所需的Tailwind 元素修饰符

    src/components/Prose.astro
    ---
    ---
    <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>
  2. 在你想要渲染 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>
贡献 社区 赞助