跳转到内容

使用 Tailwind Typography 美化渲染后的 Markdown

你可以使用 Tailwind 的 Typography 插件来美化如 Astro 的 内容集合 等来源的渲染后的 Markdown。

本指南将教你如何使用 Tailwind 的实用类创建一个可复用的 Astro 组件,以便美化你的 Markdown 内容。

前提条件

一个 Astro 项目:

设置 @tailwindcss/typography

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

npm install -D @tailwindcss/typography

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

@import 'tailwindcss';
@plugin '@tailwindcss/typography';

操作步骤

  1. 创建一个 <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 类。:::

  2. 在你想要渲染 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>

资源

贡献 社区 赞助