定制
配置和自定义 Tailwind 安装的指南。
由于 Tailwind 是一个用于构建定制用户界面的框架,因此它在设计时就考虑到了定制化。
默认情况下,Tailwind 会在项目根目录下查找可选的 tailwind.config.js
文件,您可以在其中定义任何自定义内容。
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ['./src/**/*.{html,js}'],
theme: {
colors: {
'blue': '#1fb6ff',
'purple': '#7e5bef',
'pink': '#ff49db',
'orange': '#ff7849',
'green': '#13ce66',
'yellow': '#ffc82c',
'gray-dark': '#273444',
'gray': '#8492a6',
'gray-light': '#d3dce6',
},
fontFamily: {
sans: ['Graphik', 'sans-serif'],
serif: ['Merriweather', 'serif'],
},
extend: {
spacing: {
'8xl': '96rem',
'9xl': '128rem',
},
borderRadius: {
'4xl': '2rem',
}
}
},
}
配置文件的每个部分都是可选的,因此您只需指定要更改的内容。任何缺失的部分都将返回到 Tailwind 的 default configuration。
使用安装 tailwindcss
npm 包时附带的 Tailwind CLI 实用程序为您的项目生成 Tailwind 配置文件:
npx tailwindcss init
这将在项目根目录创建一个最小的 tailwind.config.js
文件:
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [],
theme: {
extend: {},
},
plugins: [],
}
要使用 tailwind.config.js
以外的名称,请将其作为参数传递到命令行:
npx tailwindcss init tailwindcss-config.js
当您使用自定义文件名时,您需要在使用 Tailwind CLI 工具编译 CSS 时将其指定为命令行参数:
npx tailwindcss -c ./tailwindcss-config.js -i input.css -o output.css
如果您使用 Tailwind 作为 PostCSS 插件,则需要在 PostCSS 配置中指定自定义配置路径:
module.exports = {
plugins: {
tailwindcss: { config: './tailwindcss-config.js' },
},
}
或者,您可以使用 @config
指令指定自定义配置路径:
@config "./tailwindcss-config.js";
@tailwind base;
@tailwind components;
@tailwind utilities;
在 Functions & Directives 文档中了解有关 @config
指令的更多信息。
您还可以在 ESM 甚至 TypeScript 中配置 Tailwind CSS:
/** @type {import('tailwindcss').Config} */
export default {
content: [],
theme: {
extend: {},
},
plugins: [],
}
当您运行 npx tailwindcss init
时,我们会检测您的项目是否是 ES 模块,并使用正确的语法自动生成您的配置文件。
您还可以使用 --esm
标志明确生成 ESM 配置文件:
npx tailwindcss init --esm
要生成 TypeScript 配置文件,请使用 --ts
标志:
npx tailwindcss init --ts
如果您还想在 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 内部使用的 default configuration file 匹配的文件。
content
部分是您配置所有 HTML 模板、JS 组件以及任何其他包含 Tailwind 类名的文件的路径的地方。
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
'./pages/**/*.{html,js}',
'./components/**/*.{html,js}',
],
// ...
}
在 Content Configuration 文档中了解有关配置内容源的更多信息。
theme
部分是您定义调色板、字体、类型比例、边框大小、断点的地方——任何与您网站的视觉设计相关的内容。
/** @type {import('tailwindcss').Config} */
module.exports = {
// ...
theme: {
colors: {
'blue': '#1fb6ff',
'purple': '#7e5bef',
'pink': '#ff49db',
'orange': '#ff7849',
'green': '#13ce66',
'yellow': '#ffc82c',
'gray-dark': '#273444',
'gray': '#8492a6',
'gray-light': '#d3dce6',
},
fontFamily: {
sans: ['Graphik', 'sans-serif'],
serif: ['Merriweather', 'serif'],
},
extend: {
spacing: {
'8xl': '96rem',
'9xl': '128rem',
},
borderRadius: {
'4xl': '2rem',
}
}
}
}
在 theme configuration guide 中了解有关默认主题的更多信息以及如何自定义它。
plugins
部分允许您向 Tailwind 注册插件,可用于生成额外的实用程序、组件、基本样式或自定义变体。
/** @type {import('tailwindcss').Config} */
module.exports = {
// ...
plugins: [
require('@tailwindcss/forms'),
require('@tailwindcss/aspect-ratio'),
require('@tailwindcss/typography'),
require('tailwindcss-children'),
],
}
在plugin authoring guide中了解有关编写自己的插件的更多信息。
presets
部分允许您指定自己的自定义基本配置,而不是使用 Tailwind 的默认基本配置。
/** @type {import('tailwindcss').Config} */
module.exports = {
// ...
presets: [
require('@acmecorp/base-tailwind-config')
],
// Project-specific customizations
theme: {
//...
},
}
在 presets documentation 中了解有关预设的更多信息。
prefix
选项允许您为 Tailwind 生成的所有实用程序类添加自定义前缀。当在可能存在命名冲突的现有 CSS 上分层 Tailwind 时,此功能非常有用。
例如,您可以通过设置 prefix
选项来添加 tw-
前缀,如下所示:
/** @type {import('tailwindcss').Config} */
module.exports = {
prefix: 'tw-',
}
现在每个类都将使用配置的前缀生成:
.tw-text-left {
text-align: left;
}
.tw-text-center {
text-align: center;
}
.tw-text-right {
text-align: right;
}
/* etc. */
重要的是要理解,此前缀是在任何变体修饰符之后添加的。这意味着具有响应式或状态修饰符(如 sm:
或 hover:
)的类仍将首先具有响应式或状态修饰符,而您的自定义前缀将出现在冒号之后:
<div class="tw-text-lg md:tw-text-xl tw-bg-red-500 hover:tw-bg-blue-500">
<!-- -->
</div>
负值的破折号修饰符应添加到前缀之前,因此,如果您已将 tw-
配置为前缀,则 -mt-8
将变为 -tw-mt-8
:
<div class="-tw-mt-8">
<!-- -->
</div>
前缀仅添加到 Tailwind 生成的类中;不会将前缀添加到您自己的自定义类中。
这意味着如果您添加自己的自定义实用程序,如下所示:
@layer utilities {
.bg-brand-gradient { /* ... */ }
}
…生成的变体将没有您配置的前缀:
.bg-brand-gradient { /* ... */ }
.hover\:bg-brand-gradient:hover { /* ... */ }
如果您也想为自己的实用程序添加前缀,只需将前缀添加到类定义中:
@layer utilities {
.tw-bg-brand-gradient { /* ... */ }
}
important
选项可让您控制 Tailwind 的实用程序是否应标记为 !important
。当将 Tailwind 与具有高特异性选择器的现有 CSS 一起使用时,这非常有用。
要将实用程序生成为 !important
,请将配置选项中的 important
键设置为 true
:
/** @type {import('tailwindcss').Config} */
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. */
这也适用于您使用 @layer utilities
指令在 CSS 中定义的任何自定义实用程序:
/* Input */
@layer utilities {
.bg-brand-gradient {
background-image: linear-gradient(#3490dc, #6574cd);
}
}
/* Output */
.bg-brand-gradient {
background-image: linear-gradient(#3490dc, #6574cd) !important;
}
在整合第三方 JS 库(这些库会向您的元素添加内联样式)时,将 important
设置为 true
可能会引发一些问题。在这些情况下,Tailwind 的 !important
实用程序会破坏内联样式,从而破坏您的预期设计。
为了解决这个问题,您可以将 important
设置为 ID 选择器,如 #app
:
/** @type {import('tailwindcss').Config} */
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>
使用选择器策略时,请确保包含根选择器的模板文件包含在 content configuration 中,否则在构建生产时所有 CSS 都将被删除。
或者,你可以在任何实用程序开头添加 !
字符,使其变得重要:
<p class="!font-medium font-bold">
This will be medium even though bold comes later in the CSS.
</p>
!
始终位于实用程序名称的开头,位于任何变体之后,但在任何前缀之前:
<div class="sm:hover:!tw-font-bold">
这在极少数情况下很有用,因为您需要增加特殊性,因为您与某些您无法控制的风格发生冲突。
separator
选项允许您自定义使用哪个字符来分隔修饰符(屏幕尺寸,hover
,focus
等)和实用程序名称(text-center
,items-end
等)。
我们默认使用冒号(:
),但如果您使用的模板语言(如 Pug)不支持类名中的特殊字符,则更改此设置会很有用。
/** @type {import('tailwindcss').Config} */
module.exports = {
separator: '_',
}
如果您的项目不需要 Tailwind 通常默认生成的类,则 corePlugins
部分可让您完全禁用这些类。
要禁用特定的核心插件,请为 corePlugins
提供一个对象,将这些插件设置为 false
:
/** @type {import('tailwindcss').Config} */
module.exports = {
corePlugins: {
float: false,
objectFit: false,
objectPosition: false,
}
}
如果您想要安全列出应该启用的核心插件,请提供一个包含您想要使用的核心插件列表的数组:
/** @type {import('tailwindcss').Config} */
module.exports = {
corePlugins: [
'margin',
'padding',
'backgroundColor',
// ...
]
}
如果您想禁用 Tailwind 的所有核心插件并仅使用 Tailwind 作为处理您自己的自定义插件的工具,请提供一个空数组:
/** @type {import('tailwindcss').Config} */
module.exports = {
corePlugins: []
}
以下是每个核心插件的列表,供参考:
Core Plugin | Description |
---|---|
accentColor | The accent-color utilities like accent-green-800 |
accessibility | The sr-only and not-sr-only utilities |
alignContent | The align-content utilities like content-between |
alignItems | The align-items utilities like items-center |
alignSelf | The align-self utilities like self-end |
animation | The animation utilities like animate-ping |
appearance | The appearance utilities like appearance-none |
aspectRatio | The aspect-ratio utilities like aspect-square |
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-30 |
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-800 |
backgroundImage | The background-image utilities like bg-gradient-to-br |
backgroundOpacity | The background-color opacity utilities like bg-opacity-25 |
backgroundOrigin | The background-origin utilities like bg-origin-padding |
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-e-green-800 |
borderOpacity | The border-color opacity utilities like border-opacity-25 |
borderRadius | The border-radius utilities like rounded-ss-lg |
borderSpacing | The border-spacing utilities like border-spacing-x-28 |
borderStyle | The border-style utilities like border-dotted |
borderWidth | The border-width utilities like border-e-4 |
boxDecorationBreak | The box-decoration-break utilities like decoration-clone |
boxShadow | The box-shadow utilities like shadow-lg |
boxShadowColor | The box-shadow-color utilities like shadow-green-800 |
boxSizing | The box-sizing utilities like box-border |
breakAfter | The break-after utilities like break-after-avoid-page |
breakBefore | The break-before utilities like break-before-avoid-page |
breakInside | The break-inside utilities like break-inside-avoid |
brightness | The brightness utilities like brightness-100 |
captionSide | The caption-side utilities like caption-top |
caretColor | The caret-color utilities like caret-green-800 |
clear | The clear utilities like clear-left |
columns | The columns utilities like columns-auto |
contain | The contain utilities like contain-size |
container | The container component |
content | The content utilities like content-none |
contrast | The contrast utilities like contrast-100 |
cursor | The cursor utilities like cursor-grab |
display | The display utilities like table-column-group |
divideColor | The between elements border-color utilities like divide-slate-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-green-700 |
filter | The filter utilities like filter |
flex | The flex utilities like flex-auto |
flexBasis | The flex-basis utilities like basis-px |
flexDirection | The flex-direction utilities like flex-row-reverse |
flexGrow | The flex-grow utilities like flex-grow |
flexShrink | The flex-shrink utilities like flex-shrink |
flexWrap | The flex-wrap utilities like flex-wrap-reverse |
float | The float utilities like float-right |
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 oldstyle-nums |
fontWeight | The font-weight utilities like font-medium |
forcedColorAdjust | The forced-color-adjust utilities like forced-color-adjust-auto |
gap | The gap utilities like gap-x-28 |
gradientColorStops | The gradient-color-stops utilities like via-emerald-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-dense |
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-6 |
gridRowEnd | The grid-row-end utilities like row-end-7 |
gridRowStart | The grid-row-start utilities like row-start-7 |
gridTemplateColumns | The grid-template-columns utilities like grid-cols-7 |
gridTemplateRows | The grid-template-rows utilities like grid-rows-7 |
height | The height utilities like h-96 |
hueRotate | The hue-rotate utilities like hue-rotate-30 |
hyphens | The hyphens utilities like hyphens-manual |
inset | The inset utilities like end-44 |
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 |
lineClamp | The line-clamp utilities like line-clamp-4 |
lineHeight | The line-height utilities like leading-9 |
listStyleImage | The list-style-image utilities like list-image-none |
listStylePosition | The list-style-position utilities like list-inside |
listStyleType | The list-style-type utilities like list-disc |
margin | The margin utilities like me-28 |
maxHeight | The max-height utilities like max-h-44 |
maxWidth | The max-width utilities like max-w-80 |
minHeight | The min-height utilities like min-h-44 |
minWidth | The min-width utilities like min-w-36 |
mixBlendMode | The mix-blend-mode utilities like mix-blend-hard-light |
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 |
outlineColor | The outline-color utilities like outline-green-800 |
outlineOffset | The outline-offset utilities like outline-offset-2 |
outlineStyle | The outline-style utilities like outline-dashed |
outlineWidth | The outline-width utilities like outline-2 |
overflow | The overflow utilities like overflow-x-hidden |
overscrollBehavior | The overscroll-behavior utilities like overscroll-y-contain |
padding | The padding utilities like pe-28 |
placeContent | The place-content utilities like place-content-between |
placeItems | The place-items utilities like place-items-center |
placeSelf | The place-self utilities like place-self-end |
placeholderColor | The placeholder color utilities like placeholder-red-600 |
placeholderOpacity | The placeholder color opacity utilities like placeholder-opacity-25 |
pointerEvents | The pointer-events utilities like pointer-events-none |
position | The position utilities like absolute |
preflight | Tailwind's base/reset styles |
resize | The resize utilities like resize-y |
ringColor | The ring-color utilities like ring-green-800 |
ringOffsetColor | The ring-offset-color utilities like ring-offset-green-800 |
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-4 |
rotate | The rotate utilities like rotate-6 |
saturate | The saturate utilities like saturate-100 |
scale | The scale utilities like scale-x-95 |
scrollBehavior | The scroll-behavior utilities like scroll-auto |
scrollMargin | The scroll-margin utilities like scroll-me-28 |
scrollPadding | The scroll-padding utilities like scroll-pe-28 |
scrollSnapAlign | The scroll-snap-align utilities like snap-end |
scrollSnapStop | The scroll-snap-stop utilities like snap-normal |
scrollSnapType | The scroll-snap-type utilities like snap-y |
sepia | The sepia utilities like sepia-0 |
size | The size utilities like size-0.5 |
skew | The skew utilities like skew-x-12 |
space | The "space-between" utilities like space-x-4 |
stroke | The stroke utilities like stroke-green-700 |
strokeWidth | The stroke-width utilities like stroke-1 |
tableLayout | The table-layout utilities like table-auto |
textAlign | The text-align utilities like text-right |
textColor | The text-color utilities like text-green-800 |
textDecoration | The text-decoration utilities like overline |
textDecorationColor | The text-decoration-color utilities like decoration-green-800 |
textDecorationStyle | The text-decoration-style utilities like decoration-dotted |
textDecorationThickness | The text-decoration-thickness utilities like decoration-4 |
textIndent | The text-indent utilities like indent-28 |
textOpacity | The text-opacity utilities like text-opacity-50 |
textOverflow | The text-overflow utilities like overflow-ellipsis |
textTransform | The text-transform utilities like lowercase |
textUnderlineOffset | The text-underline-offset utilities like underline-offset-2 |
textWrap | The text-wrap utilities like text-nowrap |
touchAction | The touch-action utilities like touch-pan-right |
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-bottom |
visibility | The visibility utilities like invisible |
whitespace | The whitespace utilities like whitespace-pre |
width | The width utilities like w-2.5 |
willChange | The will-change utilities like will-change-scroll |
wordBreak | The word-break utilities like break-words |
zIndex | The z-index utilities like z-30 |
对于需要使用不同的 Tailwind 配置生成多个 CSS 文件的项目,请使用 @config
指令指定每个 CSS 入口点应使用哪个配置文件:
@config "./tailwind.site.config.js";
@tailwind base;
@tailwind components;
@tailwind utilities;
在 Functions & Directives 文档中了解有关 @config
指令的更多信息。
在您自己的客户端 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 之类的工具在构建时生成配置的静态版本。
我们为 tailwind.config.js
文件提供了第一方 TypeScript 类型,它为您提供了各种有用的 IDE 支持,并且使您无需过多参考文档即可更轻松地更改配置。
使用 Tailwind CLI 生成的配置文件默认包含必要的类型注释,但要手动配置 TypeScript 类型,只需在配置对象上方添加类型注释:
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
// ...
],
theme: {
extend: {},
},
plugins: [],
}