在 Tailwind 的基底上增加屬於自己的基底(全域)樣式的最佳實踐
基底(全域)樣式是位於樣式表開頭的樣式,它可以用來定義基本 HTML 元素如:<a>
標籤、標題等的預設值,也可以用在有目的的重置,像是常見的 box-sizing reset。
Tailwind 提供了一組有用的基底樣式,稱為 Preflight,實際上它就是 modern-normalize 再加上一些些額外的樣式。
對於大多數的專案來說,Preflight 是一個很好的起點,但是如果您想添加自訂的其他基底樣式,以下是一些慣用作法的建議。
如果你只是想為 html
或 body
等元素設定某種基底樣式,只需要將現有的 class 加入到 HTML 中,不需要撰寫新的 CSS:
<!doctype html>
<html lang="zh-TW" class="text-gray-900 leading-tight">
<!-- ... -->
<body class="min-h-screen bg-gray-100">
<!-- ... -->
</body>
</html>
如果要將某些基底樣式應用於特定元素,最簡單的方法是單純把它加到 CSS 中。
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
h1 {
@apply text-2xl;
}
h2 {
@apply text-xl;
}
}
透過 @layer
指令,Tailwind 將自動把這些樣式移到 @tailwind base
相同的位置,以避免發生一些意外問題。
使用 @layer
指令還能告訴 Tailwind 在清理基底樣式時該保留哪些樣式,請閱讀 documentation on optimizing for production 了解更多細節。
最好使用 @apply 或 theme() 定義這些樣式,以避免它們意外偏離你的設計系統。
你可以用相同的方式為所使用的任何自訂字體增加 @font-face
規則:
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
@font-face {
font-family: Proxima Nova;
font-weight: 400;
src: url(/fonts/proxima-nova/400-regular.woff) format("woff");
}
@font-face {
font-family: Proxima Nova;
font-weight: 500;
src: url(/fonts/proxima-nova/500-medium.woff) format("woff");
}
}
你還可以透過 writing a plugin 並使用 addBase
函式來增加基底樣式:
// tailwind.config.js
const plugin = require('tailwindcss/plugin')
module.exports = {
plugins: [
plugin(function({ addBase, theme }) {
addBase({
'h1': { fontSize: theme('fontSize.2xl') },
'h2': { fontSize: theme('fontSize.xl') },
'h3': { fontSize: theme('fontSize.lg') },
})
})
]
}
任何使用 addBase
增加的樣式,都會與 Tailwind 的其他基底樣式一起加入到 base
層中。