# TailwindCSS 文章快速排版 : 使用 Typography 擴充套件 2024/02/18 [toc] ## 為什麼要使用 Typography? 在幫網頁文章排版的時候,我們可能經常使用 TailwindCSS 的一些 class 來調整文字大小和間隔距離,例如: - 文字大小:`text-sm`、`text-lg`、`text-xl` ... - 字元間距:`tracking-tight`、`tracking-wide`、`tracking-wider` ... - 行距:`leading-6`、`leading-relaxed`、`leading-loose` ... 使用這些 class 可以依照網頁的需求彈性調整文章的排版,但如果不想要花費時間思考特定的排版,希望能夠快速套用到大量文章,並提升閱讀舒適度,那麼使用 TailwindCSS 的官方擴充套件"Typography"會非常省事! ## 安裝與設定 前提:專案已安裝並設定好TailwindCSS。 首先安裝 TailwindCSS plugin Typography 擴充套件: ``` npm install -D @tailwindcss/typography ``` or ``` pnpm add @tailwindcss/typography ``` 由於是擴充套件,我們需要將其引入`tailwind.config.js`檔案中: ``` /** @type {import('tailwindcss').Config} */ module.exports = { theme: { // ... }, plugins: [ require('@tailwindcss/typography'), // ... ], } ``` ## 套用 Typography `prose` 為 Typography 專用的 class 關鍵字,使用 Typography 樣式時必須要有 `prose` 並加上`prose-xxxx`樣式才可套用設定,例如: ``` <article class="prose md:prose-lg">{{ markdown }}</article> ``` ## Typography 實用的設定 ### 自訂顏色主題 例如在 tailwind.config.js 文件中自訂一個 custom 主題,將文字和標題設定為淺灰: ``` module.exports = { theme: { extend: { typography: ({ theme }) => ({ custom: { css: { '--tw-prose-body': theme('colors.gray[100]'), '--tw-prose-headings': theme('colors.gray[100]'), }, }, }), }, }, plugins: [ require('@tailwindcss/typography'), // ... ], } ``` 在元素中使用該主題: ``` <article class="prose prose-custom"> <h1>Garlic bread with cheese: What the science tells us</h1> <p> For years parents have espoused the health benefits of eating garlic bread with cheese to their children, with the food earning such an iconic status in our culture that kids will often dress up as warm, cheesy loaf for Halloween. </p> <!-- ... --> </article> ``` ### 搭配深色/淺色模式 使用`prose-invert`屬性反轉預設字體顏色。例如預設的文字顏色為黑色,那麼使用該屬性可以將文字改為白色,特別適用於設定深色模式。 ``` <article class="prose dark:prose-invert">{{ markdown }}</article> ``` ### 修改文章寬度 一開始使用 Typography 應用在網頁文章上時,就發現文章的寬度比網頁寬度窄很多,這是因為 Typography 預設一個最大的文章寬度以適合閱讀,若我們網頁設計的文章區域較寬,想要使用自訂的文章寬度,只要添加 class:`max-w-none` ``` <article class="prose max-w-none"> <h1>Garlic bread with cheese: What the science tells us</h1> <p> For years parents have espoused the health benefits of eating garlic bread with cheese to their children, with the food earning such an iconic status in our culture that kids will often dress up as warm, cheesy loaf for Halloween. </p> <!-- ... --> </article> ``` 這樣就可以覆寫預設的文章寬度囉! 以上就是很實用又快速的 Typography 設定,還有更多功能與自訂樣式可以參考以下官方文件連結~ ## 參考 - TailwindCSS Typography 官方文件 https://github.com/tailwindlabs/tailwindcss-typography