配置和定制 Tailwind 安装的指南。
因为 Tailwind 是一个构建定制用户界面的框架,所以从开始设计时便考虑了定制。
默认情况下,Tailwind 将在项目的根目录中查找一个可选的 tailwind.config.js
的文件,您可以在其中定义任何自定义选项。
// Example `tailwind.config.js` file
const colors = require('tailwindcss/colors')
module.exports = {
theme: {
colors: {
gray: colors.coolGray,
blue: colors.lightBlue,
red: colors.rose,
pink: colors.fuchsia,
},
fontFamily: {
sans: ['Graphik', 'sans-serif'],
serif: ['Merriweather', 'serif'],
},
extend: {
spacing: {
'128': '32rem',
'144': '36rem',
},
borderRadius: {
'4xl': '2rem',
}
}
},
variants: {
extend: {
borderColor: ['focus-visible'],
opacity: ['disabled'],
}
}
}
配置文件的每个部分都是可选的,因此您只需指定要更改的内容即可。任何缺少的部分将会使用 Tailwind 的 默认配置。
使用 Tailwind CLI 功能生成 Tailwind 配置文件,Tailwind CLI 在您安装 tailwindcss
npm 软件包时已经附带安装过。
npx tailwindcss init
这将在项目的根目录下创建一个最小文件 tailwind.config.js
:
// tailwind.config.js
module.exports = {
purge: [],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [],
}
要使用 tailwind.config.js
之外的文件名,请在命令行中将其做为参数传入:
npx tailwindcss init tailwindcss-config.js
如果使用自定义文件名,则在 PostCSS 配置中将 Tailwind 做为插件引入时,也需要指定它:
// postcss.config.js
module.exports = {
plugins: {
tailwindcss: { config: './tailwindcss-config.js' },
},
}
如果您想在生成 tailwind.config.js
文件的同时也生成一个基础的 postcss.config.js
文件,请使用 -p
标志。
npx tailwindcss init -p
这将在您的项目中生成一个 postcss.config.js
文件,如下所示:
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
对于大多数用户,我们建议您尽量减少配置文件,只指定您想自定义的内容。
如果您希望构建一个完整的配置文件,其中包括 Tailwind的 所有默认配置,请使用以下 --full
选项:
npx tailwindcss init --full
您将得到一个与 Tailwind 内部使用的 默认配置文件 一致的文件。
在 theme
部分中,您可以定义调色板、字体、类型比例、边框大小、断点等任何与您网站视觉设计有关的东西。
// tailwind.config.js
module.exports = {
theme: {
colors: {
gray: colors.coolGray,
blue: colors.lightBlue,
red: colors.rose,
pink: colors.fuchsia,
},
fontFamily: {
sans: ['Graphik', 'sans-serif'],
serif: ['Merriweather', 'serif'],
},
extend: {
spacing: {
'128': '32rem',
'144': '36rem',
},
borderRadius: {
'4xl': '2rem',
}
}
}
}
了解更多关于默认主题及如何对其定制的信息,参考 主题配置指南 。
variants
部分允许您控制为每个核心功能插件生成哪些 变体 。
// tailwind.config.js
module.exports = {
variants: {
fill: [],
extend: {
borderColor: ['focus-visible'],
opacity: ['disabled'],
}
},
}
查看 变体配置指南 了解更多信息。
plugins
部分允许您向 Tailwind 注册插件,这些插件可用于生成额外功能类、组件、基本样式或自定义变体。
// tailwind.config.js
module.exports = {
plugins: [
require('@tailwindcss/forms'),
require('@tailwindcss/aspect-ratio'),
require('@tailwindcss/typography'),
require('tailwindcss-children'),
],
}
了解更多关于编写插件的信息,请查看 插件编写指南 。
presets
部分允许您指定自己的自定义基本配置,来替代 Tailwind 的默认基本配置。
// tailwind.config.js
module.exports = {
presets: [
require('@acmecorp/base-tailwind-config')
],
// Project-specific customizations
theme: {
//...
},
// ...
}
查看 预设文档 了解更多关于预设的信息。
prefix
选项允许您为所有 Tailwind 生成的功能类添加一个自定义前缀。当 Tailwind 和一个已有的 CSS 存在命名冲突时,这个功能会非常有用。
例如,您可以通过这样设置来添加 tw-
前缀:
// tailwind.config.js
module.exports = {
prefix: 'tw-',
}
现在,将使用配置的前缀生成每个类。
.tw-text-left {
text-align: left;
}
.tw-text-center {
text-align: center;
}
.tw-text-right {
text-align: right;
}
/* etc. */
请一定要理解,这个前缀是在任何变体前缀之后添加的。这意味着,带有响应式或者状态前缀(如 sm:
or hover:
)的类仍然会最先出现,自定义前缀要写在冒号后面。
<div class="tw-text-lg md:tw-text-xl tw-bg-red-500 hover:tw-bg-blue-500">
<!-- -->
</div>
前缀仅会被添加到 Tailwind 生成的类中;您自己的自定义类中将不会被添加前缀。
这意味着,如果您像这样添加自己的响应式功能类:
@variants hover {
.bg-brand-gradient { /* ... */ }
}
... 生成的响应式类将不会带有您配置的前缀:
.bg-brand-gradient { /* ... */ }
.hover\:bg-brand-gradient:hover { /* ... */ }
如果您也想给您自己的功能类添加前缀,只需要把前缀添加到类定义中即可:
@variants hover {
.tw-bg-brand-gradient { /* ... */ }
}
important
选项允许您控制是否将 Tailwind 的功能类标记为 !important
。当您将 Tailwind 与已存在的具有非常特殊的选择器的 CSS 一起使用时,这可能会非常有用。
要生成 !important
的功能类,在您的配置选项中把 important
键设置为 true
:
// tailwind.config.js
module.exports = {
important: true,
}
现在,所有的 Tailwind 功能类都将被生成 !important
:
.leading-none {
line-height: 1 !important;
}
.leading-tight {
line-height: 1.25 !important;
}
.leading-snug {
line-height: 1.375 !important;
}
/* etc. */
注意:启用此选项不会将您的任何自定义功能类标记为 !important
。
如果您想把自己的功能也标记为 !important
,只需要自己在每个声明末尾添加 !important
:
@responsive {
.bg-brand-gradient {
background-image: linear-gradient(#3490dc, #6574cd) !important;
}
}
在合并第三方 JS 库且这些库会为您的元素添加内联样式的时候,设置 important
为 true
会引入一些问题。在这种情况下,Tailwind 的 !important
功能会覆盖内联样式,这会破坏您的预期设计。
为了解决这个问题,您可以为一个 ID 选择器设置 important
,比如 #app
:
// tailwind.config.js
module.exports = {
important: '#app',
}
这个配置将在您所有的功能类前加上给定的选择器,有效地增加它们的特殊性,而实际上并没有使它们变得 !important
。
当您指定了 important
选择器后,您需要确保您的网站的根元素与之匹配。 使用上面的例子,我们需要将根元素的 id
属性设置为 app
,以使样式正常工作。
当您的配置都设置好,且您的根元素与 Tailwind 配置中的选择器相匹配后,Tailwind 的所有功能类将有足够高的特异性来击败您的项目中使用的其他类,但并不干扰内联样式。
<html>
<!-- ... -->
<style>
.high-specificity .nested .selector {
color: blue;
}
</style>
<body id="app">
<div class="high-specificity">
<div class="nested">
<!-- Will be red-500 -->
<div class="selector text-red-500"><!-- ... --></div>
</div>
</div>
<!-- Will be #bada55 -->
<div class="text-red-500" style="color: #bada55;"><!-- ... --></div>
</body>
</html>
separator
选项可以让您自定义应该使用什么字符或字符串来分隔变体前缀(屏幕大小、hover
、focus
等)和类名(text-center
、items-end
等)。
我们默认使用冒号(:
),但是如果您使用的是像 Pug 这样的模板语言,不支持在类名中使用特殊字符,那么改变这个冒号就会很有用。
// tailwind.config.js
module.exports = {
separator: '_',
}
如果您使用 extend
功能启用额外的变体,这些变体会自动排序,以遵守合理的默认变体顺序。
如果有必要,您可以在 variantOrder
键下面自定义变体顺序:
// tailwind.config.js
module.exports = {
// ...
variantOrder: [
'first',
'last',
'odd',
'even',
'visited',
'checked',
'group-hover',
'group-focus',
'focus-within',
'hover',
'focus',
'focus-visible',
'active',
'disabled',
]
}
corePlugins
部分允许您完全禁用掉那些 Tailwind 默认生成的类,如果您的项目不需要。
如果您没有提供任何 corePlugins
配置,则默认情况下将启用所有的核心插件。
// tailwind.config.js
module.exports = {
// ...
}
如果您想禁用特定的核心插件,为 corePlugins
提供一个对象,将这些插件设置为false
。
// tailwind.config.js
module.exports = {
corePlugins: {
float: false,
objectFit: false,
objectPosition: false,
}
}
如果您想安全地列出哪些核心插件应该被启用,请提供一个数组,其中包括您想使用的核心插件的列表。
// tailwind.config.js
module.exports = {
corePlugins: [
'margin',
'padding',
'backgroundColor',
// ...
]
}
如果您想禁用所有 Tailwind 的核心插件,并简单地使用 Tailwind 作为处理您自己的自定义插件的工具,那么只需提供一个空数组。
// tailwind.config.js
module.exports = {
corePlugins: []
}
下面是每个核心插件的列表,供参考:
Core Plugin | Description |
---|---|
preflight | Tailwind's base/reset styles |
container | The container component |
accessibility | The sr-only and not-sr-only utilities |
alignContent | The align-content utilities like content-end |
alignItems | The align-items utilities like items-center |
alignSelf | The align-self utilities like self-end |
animation | The animation utilities like animate-none |
appearance | The appearance utilities like appearance-none |
backdropBlur | The backdrop-blur utilities like backdrop-blur-md |
backdropBrightness | The backdrop-brightness utilities like backdrop-brightness-100 |
backdropContrast | The backdrop-contrast utilities like backdrop-contrast-100 |
backdropFilter | The backdrop-filter utilities like backdrop-filter |
backdropGrayscale | The backdrop-grayscale utilities like backdrop-grayscale-0 |
backdropHueRotate | The backdrop-hue-rotate utilities like backdrop-hue-rotate-180 |
backdropInvert | The backdrop-invert utilities like backdrop-invert-0 |
backdropOpacity | The backdrop-opacity utilities like backdrop-opacity-50 |
backdropSaturate | The backdrop-saturate utilities like backdrop-saturate-100 |
backdropSepia | The backdrop-sepia utilities like backdrop-sepia-0 |
backgroundAttachment | The background-attachment utilities like bg-local |
backgroundBlendMode | The background-blend-mode utilities like bg-blend-color-burn |
backgroundClip | The background-clip utilities like bg-clip-padding |
backgroundColor | The background-color utilities like bg-green-700 |
backgroundImage | The background-image utilities like bg-gradient-to-br |
backgroundOpacity | The background-color opacity utilities like bg-opacity-25 |
backgroundPosition | The background-position utilities like bg-left-top |
backgroundRepeat | The background-repeat utilities like bg-repeat-x |
backgroundSize | The background-size utilities like bg-cover |
blur | The blur utilities like blur-md |
borderCollapse | The border-collapse utilities like border-collapse |
borderColor | The border-color utilities like border-green-700 |
borderOpacity | The border-color opacity utilities like border-opacity-25 |
borderRadius | The border-radius utilities like rounded-l-3xl |
borderStyle | The border-style utilities like border-dotted |
borderWidth | The border-width utilities like border-l-2 |
boxDecorationBreak | The box-decoration-break utilities like decoration-slice |
boxShadow | The box-shadow utilities like shadow-lg |
boxSizing | The box-sizing utilities like box-border |
brightness | The brightness utilities like brightness-100 |
clear | The clear utilities like clear-right |
contrast | The contrast utilities like contrast-100 |
cursor | The cursor utilities like cursor-wait |
display | The display utilities like table-column-group |
divideColor | The between elements border-color utilities like divide-gray-500 |
divideOpacity | The divide-opacity utilities like divide-opacity-50 |
divideStyle | The divide-style utilities like divide-dotted |
divideWidth | The between elements border-width utilities like divide-x-2 |
dropShadow | The drop-shadow utilities like drop-shadow-lg |
fill | The fill utilities like fill-current |
filter | The filter utilities like filter |
flex | The flex utilities like flex-auto |
flexDirection | The flex-direction utilities like flex-row-reverse |
flexGrow | The flex-grow utilities like flex-grow-0 |
flexShrink | The flex-shrink utilities like flex-shrink-0 |
flexWrap | The flex-wrap utilities like flex-wrap-reverse |
float | The float utilities like float-left |
fontFamily | The font-family utilities like font-serif |
fontSize | The font-size utilities like text-3xl |
fontSmoothing | The font-smoothing utilities like antialiased |
fontStyle | The font-style utilities like italic |
fontVariantNumeric | The font-variant-numeric utilities like lining-nums |
fontWeight | The font-weight utilities like font-medium |
gap | The gap utilities like gap-x-28 |
gradientColorStops | The gradient-color-stops utilities like via-green-700 |
grayscale | The grayscale utilities like grayscale-0 |
gridAutoColumns | The grid-auto-columns utilities like auto-cols-min |
gridAutoFlow | The grid-auto-flow utilities like grid-flow-col |
gridAutoRows | The grid-auto-rows utilities like auto-rows-min |
gridColumn | The grid-column utilities like col-span-6 |
gridColumnEnd | The grid-column-end utilities like col-end-7 |
gridColumnStart | The grid-column-start utilities like col-start-7 |
gridRow | The grid-row utilities like row-span-3 |
gridRowEnd | The grid-row-end utilities like row-end-4 |
gridRowStart | The grid-row-start utilities like row-start-4 |
gridTemplateColumns | The grid-template-columns utilities like grid-cols-7 |
gridTemplateRows | The grid-template-rows utilities like grid-rows-4 |
height | The height utilities like h-64 |
hueRotate | The hue-rotate utilities like hue-rotate-180 |
inset | The inset utilities like bottom-10 |
invert | The invert utilities like invert-0 |
isolation | The isolation utilities like isolate |
justifyContent | The justify-content utilities like justify-center |
justifyItems | The justify-items utilities like justify-items-end |
justifySelf | The justify-self utilities like justify-self-end |
letterSpacing | The letter-spacing utilities like tracking-normal |
lineHeight | The line-height utilities like leading-9 |
listStylePosition | The list-style-position utilities like list-inside |
listStyleType | The list-style-type utilities like list-disc |
margin | The margin utilities like ml-8 |
maxHeight | The max-height utilities like max-h-32 |
maxWidth | The max-width utilities like max-w-5xl |
minHeight | The min-height utilities like min-h-full |
minWidth | The min-width utilities like min-w-full |
mixBlendMode | The mix-blend-mode utilities like mix-blend-color-burn |
objectFit | The object-fit utilities like object-fill |
objectPosition | The object-position utilities like object-left-top |
opacity | The opacity utilities like opacity-50 |
order | The order utilities like order-8 |
outline | The outline utilities like outline-white |
overflow | The overflow utilities like overflow-y-auto |
overscrollBehavior | The overscroll-behavior utilities like overscroll-y-contain |
padding | The padding utilities like pr-4 |
placeContent | The place-content utilities like place-content-between |
placeholderColor | The placeholder color utilities like placeholder-red-600 |
placeholderOpacity | The placeholder color opacity utilities like placeholder-opacity-25 |
placeItems | The place-items utilities like place-items-end |
placeSelf | The place-self utilities like place-self-end |
pointerEvents | The pointer-events utilities like pointer-events-none |
position | The position utilities like absolute |
resize | The resize utilities like resize-y |
ringColor | The ring-color utilities like ring-green-700 |
ringOffsetColor | The ring-offset-color utilities like ring-offset-green-700 |
ringOffsetWidth | The ring-offset-width utilities like ring-offset-2 |
ringOpacity | The ring-opacity utilities like ring-opacity-50 |
ringWidth | The ring-width utilities like ring-2 |
rotate | The rotate utilities like rotate-180 |
saturate | The saturate utilities like saturate-100 |
scale | The scale utilities like scale-x-95 |
sepia | The sepia utilities like sepia-0 |
skew | The skew utilities like -skew-x-1 |
space | The "space-between" utilities like space-x-4 |
stroke | The stroke utilities like stroke-current |
strokeWidth | The stroke-width utilities like stroke-1 |
tableLayout | The table-layout utilities like table-auto |
textAlign | The text-align utilities like text-center |
textColor | The text-color utilities like text-green-700 |
textDecoration | The text-decoration utilities like line-through |
textOpacity | The text-opacity utilities like text-opacity-50 |
textOverflow | The text-overflow utilities like overflow-ellipsis |
textTransform | The text-transform utilities like lowercase |
transform | The transform utility (for enabling transform features) |
transformOrigin | The transform-origin utilities like origin-bottom-right |
transitionDelay | The transition-delay utilities like delay-200 |
transitionDuration | The transition-duration utilities like duration-200 |
transitionProperty | The transition-property utilities like transition-colors |
transitionTimingFunction | The transition-timing-function utilities like ease-in |
translate | The translate utilities like -translate-x-full |
userSelect | The user-select utilities like select-text |
verticalAlign | The vertical-align utilities like align-middle |
visibility | The visibility utilities like visible |
whitespace | The whitespace utilities like whitespace-pre |
width | The width utilities like w-0.5 |
wordBreak | The word-break utilities like break-words |
zIndex | The z-index utilities like z-30 |
在您的客户端 JavaScript 中引用配置的值往往非常有用。例如,在 React 或者 Vue 组件中动态应用内联样式的时候需要获取您的主题的配置值。
为了简化此操作,Tailwind 提供了一个 resolveConfig
助手函数,可以用来生成一个配置对象的完全合并的版本:
import resolveConfig from 'tailwindcss/resolveConfig'
import tailwindConfig from './tailwind.config.js'
const fullConfig = resolveConfig(tailwindConfig)
fullConfig.theme.width[4]
// => '1rem'
fullConfig.theme.screens.md
// => '768px'
fullConfig.theme.boxShadow['2xl']
// => '0 25px 50px -12px rgba(0, 0, 0, 0.25)'
请注意,这会过滤性的引入一些构建时依赖,从而导致更大的客户端文件尺寸。为了避免这种情况,我们推荐使用 babel-plugin-preval 之类的工具在构建时生成一个配置的静态版本。