1. 定制化
  2. 主题配置

tailwind.config.js 文件中的 theme 部分是你定义项目的颜色调色板、字体大小比例、字体、断点、边框半径值等的地方。

🌐 The theme section of your tailwind.config.js file is where you define your project’s color palette, type scale, fonts, breakpoints, border radius values, and more.

tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
  theme: {
    screens: {
      sm: '480px',
      md: '768px',
      lg: '976px',
      xl: '1440px',
    },
    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: {
        '128': '32rem',
        '144': '36rem',
      },
      borderRadius: {
        '4xl': '2rem',
      }
    }
  }
}

我们提供了一个合理的默认主题,其中包含非常丰富的初始值,帮助你快速入手,但不要害怕更改或扩展它;我们鼓励你根据设计目标尽可能地进行自定义。

🌐 We provide a sensible default theme with a very generous set of values to get you started, but don’t be afraid to change it or extend it; you’re encouraged to customize it as much as you need to fit the goals of your design.


主题结构(Theme structure)

theme 对象包含 screenscolorsspacing 的键,以及每个可自定义的 核心插件 的键。

🌐 The theme object contains keys for screens, colors, and spacing, as well as a key for each customizable core plugin.

请参阅主题配置参考默认主题以获取完整的主题选项列表。

🌐 See the theme configuration reference or the default theme for a complete list of theme options.

屏幕(Screens)

screens 键允许你自定义项目中的响应断点。

🌐 The screens key allows you to customize the responsive breakpoints in your project.

tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
  theme: {
    screens: {
      'sm': '640px',
      'md': '768px',
      'lg': '1024px',
      'xl': '1280px',
      '2xl': '1536px',
    }
  }
}

要了解更多信息,请参阅断点自定义文档

🌐 To learn more, see the breakpoint customization documentation.

颜色(Colors)

colors 键允许你自定义项目的全局颜色调色板。

🌐 The colors key allows you to customize the global color palette for your project.

tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
  theme: {
    colors: {
      transparent: 'transparent',
      black: '#000',
      white: '#fff',
      gray: {
        100: '#f7fafc',
        // ...
        900: '#1a202c',
      },

      // ...
    }
  }
}

默认情况下,这些颜色会被所有与颜色相关的核心插件继承,例如 backgroundColorborderColortextColor 等。

🌐 By default, these colors are inherited by all color-related core plugins, like backgroundColor, borderColor, textColor, and others.

要了解更多信息,请参阅 颜色自定义文档

🌐 To learn more, see the color customization documentation.

间距(Spacing)

spacing 键允许你自定义项目的全局间距和尺寸比例。

🌐 The spacing key allows you to customize the global spacing and sizing scale for your project.

tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
  theme: {
    spacing: {
      px: '1px',
      0: '0',
      0.5: '0.125rem',
      1: '0.25rem',
      1.5: '0.375rem',
      2: '0.5rem',
      2.5: '0.625rem',
      3: '0.75rem',
      3.5: '0.875rem',
      4: '1rem',
      5: '1.25rem',
      6: '1.5rem',
      7: '1.75rem',
      8: '2rem',
      9: '2.25rem',
      10: '2.5rem',
      11: '2.75rem',
      12: '3rem',
      14: '3.5rem',
      16: '4rem',
      20: '5rem',
      24: '6rem',
      28: '7rem',
      32: '8rem',
      36: '9rem',
      40: '10rem',
      44: '11rem',
      48: '12rem',
      52: '13rem',
      56: '14rem',
      60: '15rem',
      64: '16rem',
      72: '18rem',
      80: '20rem',
      96: '24rem',
    },
  }
}

默认情况下,这些值会被 paddingmarginwidthheightmaxHeightflex-basisgapinsetspacetranslatescrollMarginscrollPaddingtextIndent 核心插件继承。

🌐 By default, these values are inherited by the padding, margin, width, height, maxHeight, flex-basis, gap, inset, space, translate, scrollMargin, scrollPadding, and textIndent core plugins.

要了解更多信息,请参阅 间距自定义文档

🌐 To learn more, see the spacing customization documentation.

核心插件(Core plugins)

theme 部分的其余部分用于配置每个核心插件可用的值。

🌐 The rest of the theme section is used to configure which values are available for each individual core plugin.

例如,borderRadius 键可以让你自定义将生成哪些边框半径实用工具:

🌐 For example, the borderRadius key lets you customize which border radius utilities will be generated:

module.exports = {
  theme: {
    borderRadius: {
      'none': '0',
      'sm': '.125rem',
      DEFAULT: '.25rem',
      'lg': '.5rem',
      'full': '9999px',
    },
  }
}

键决定生成类的后缀,值决定实际 CSS 声明的值。

🌐 The keys determine the suffix for the generated classes, and the values determine the value of the actual CSS declaration.

上面的示例 borderRadius 配置将生成以下 CSS 类:

🌐 The example borderRadius configuration above would generate the following CSS classes:

.rounded-none { border-radius: 0 }
.rounded-sm   { border-radius: .125rem }
.rounded      { border-radius: .25rem }
.rounded-lg   { border-radius: .5rem }
.rounded-full { border-radius: 9999px }

你会注意到,在主题配置中使用键 DEFAULT 会创建一个没有后缀的类 rounded。这是 Tailwind 中的常用约定,并且所有核心插件都支持这种做法。

🌐 You’ll notice that using a key of DEFAULT in the theme configuration created the class rounded with no suffix. This is a common convention in Tailwind and is supported by all core plugins.

要了解有关自定义特定核心插件的更多信息,请访问该插件的文档。

🌐 To learn more about customizing a specific core plugin, visit the documentation for that plugin.

有关可用主题属性及其默认值的完整参考,请参阅默认主题配置

🌐 For a complete reference of available theme properties and their default values, see the default theme configuration.


自定义默认主题(Customizing the default theme)

开箱即用时,你的项目将自动继承默认主题配置中的值。如果你想自定义默认主题,根据你的目标,你有几种不同的选项。

🌐 Out of the box, your project will automatically inherit the values from the default theme configuration. If you would like to customize the default theme, you have a few different options depending on your goals.

扩展默认主题(Extending the default theme)

如果你想保留主题选项的默认值,但又想添加新值,请在你的配置文件中将扩展添加到 theme.extend 键下。该键下的值会与现有的 theme 值合并,并自动作为可用的新类供你使用。

🌐 If you’d like to preserve the default values for a theme option but also add new values, add your extensions under the theme.extend key in your configuration file. Values under this key are merged with existing theme values and automatically become available as new classes that you can use.

例如,这里我们扩展了 fontFamily 属性,以添加可以更改元素字体的 font-display 类:

🌐 As an example, here we extend the fontFamily property to add the font-display class that can change the font used on an element:

tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
  theme: {
    extend: {
      fontFamily: {
        display: 'Oswald, ui-serif', // Adds a new `font-display` class
      }
    }
  }
}

将其添加到主题后,你可以像使用其他字体家族工具一样使用它:

🌐 After adding this to your theme you can use it just like any other font family utility:

<h1 class="font-display">
  This uses the Oswald font
</h1>

在某些情况下,属性映射到可以放在工具前面的变体,以有条件地应用其样式。例如,要添加一个像现有响应式屏幕一样工作的 3xl 屏幕尺寸,可以在 screens 键下添加一个属性:

🌐 In some cases, properties map to variants that can be placed in front of a utility to conditionally apply its styles. For example, to add a 3xl screen size that works just like the existing responsive screens, add a property under the screens key:

tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
  theme: {
    extend: {
      screens: {
        '3xl': '1600px', // Adds a new `3xl:` screen variant
      }
    }
  }
}

通过这个新增,你可以在现有的响应式变体如 smmdlg 等旁边使用一个新的 3xl 屏幕尺寸。你可以在使用工具类前先使用这个新变体:

🌐 With this addition, a new 3xl screen size is made available alongside the existing responsive variants like sm, md, lg, etc. You can use this new variant by placing it before a utility class:

<blockquote class="text-base md:text-md 3xl:text-lg">
  Oh I gotta get on that internet, I'm late on everything!
</blockquote>

覆盖默认主题(Overriding the default theme)

要覆盖默认主题中的选项,请将你的覆盖内容直接添加到 tailwind.config.jstheme 部分下:

🌐 To override an option in the default theme, add your overrides directly under the theme section of your tailwind.config.js:

tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
  theme: {
    // Replaces all of the default `opacity` values
    opacity: {
      '0': '0',
      '20': '0.2',
      '40': '0.4',
      '60': '0.6',
      '80': '0.8',
      '100': '1',
    }
  }
}

这将完全替换 Tailwind 对该键的默认配置,因此在上面的示例中,将不会生成任何默认的不透明度实用工具。

🌐 This will completely replace Tailwind’s default configuration for that key, so in the example above none of the default opacity utilities would be generated.

任何你未提供的键都将从默认主题继承,因此在上面的示例中,像颜色、间距、边框半径、背景位置等的默认主题配置将被保留。

🌐 Any keys you do not provide will be inherited from the default theme, so in the above example, the default theme configuration for things like colors, spacing, border-radius, background-position, etc. would be preserved.

当然,你可以在同一个配置中既重写默认主题的某些部分,又扩展默认主题的其他部分:

🌐 You can of course both override some parts of the default theme and extend other parts of the default theme within the same configuration:

tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
  theme: {
    opacity: {
      '0': '0',
      '20': '0.2',
      '40': '0.4',
      '60': '0.6',
      '80': '0.8',
      '100': '1',
    },
    extend: {
      screens: {
        '3xl': '1600px',
      }
    }
  }
}

引用其他值(Referencing other values)

如果你需要在主题中引用其他值,可以通过提供一个闭包而不是静态值来实现。闭包会接收一个对象,该对象包含一个 theme() 函数,你可以使用点符号通过它查找主题中的其他值。

🌐 If you need to reference another value in your theme, you can do so by providing a closure instead of a static value. The closure will receive an object that includes a theme() function that you can use to look up other values in your theme using dot notation.

例如,你可以通过在 backgroundSize 配置中引用 theme('spacing'),为间距刻度中的每个值生成 background-size 工具类:

🌐 For example, you could generate background-size utilities for every value in your spacing scale by referencing theme('spacing') in your backgroundSize configuration:

tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
  theme: {
    spacing: {
      // ...
    },
    backgroundSize: ({ theme }) => ({
      auto: 'auto',
      cover: 'cover',
      contain: 'contain',
      ...theme('spacing')
    })
  }
}

theme() 函数尝试从完全合并的主题对象中查找你要寻找的值,因此它可以引用你自己定制的内容以及默认主题值。它还会递归地工作,所以只要链的末端有一个静态值,它就能够解析你要寻找的值。

🌐 The theme() function attempts to find the value you are looking for from the fully merged theme object, so it can reference your own customizations as well as the default theme values. It also works recursively, so as long as there is a static value at the end of the chain it will be able to resolve the value you are looking for.

请注意,你只能在顶层主题键中使用这种闭包,而不能在每个部分内部的键中使用。

🌐 Note that you can only use this kind of closure with top-level theme keys, not the keys inside of each section.

你不能对单个值使用函数

tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
  theme: {
    fill: {
      gray: ({ theme }) => theme('colors.gray')
    }
  }
}

为顶层主题键使用函数

tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
  theme: {
    fill: ({ theme }) => ({
      gray: theme('colors.gray')
    })
  }
}

引用默认主题(Referencing the default theme)

如果你因为某种原因想引用默认主题中的某个值,可以从 tailwindcss/defaultTheme 导入它。

🌐 If you’d like to reference a value in the default theme for any reason, you can import it from tailwindcss/defaultTheme.

一个有用的例子是,如果你想向 Tailwind 的默认字体堆栈中添加字体族:

🌐 One example of where this is useful is if you’d like to add a font family to one of Tailwind’s default font stacks:

tailwind.config.js
const defaultTheme = require('tailwindcss/defaultTheme')

module.exports = {
  theme: {
    extend: {
      fontFamily: {
        sans: [
          'Lato',
          ...defaultTheme.fontFamily.sans,
        ]
      }
    }
  }
}

禁用整个核心插件(Disabling an entire core plugin)

如果你不希望为某个核心插件生成任何类,最好在你的 corePlugins 配置中将该插件设置为 false,而不是在你的 theme 配置中为该键提供一个空对象。

🌐 If you don’t want to generate any classes for a certain core plugin, it’s better to set that plugin to false in your corePlugins configuration than to provide an empty object for that key in your theme configuration.

不要在你的主题配置中分配一个空对象

tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
  theme: {
    opacity: {},
  }
}

在你的 corePlugins 配置中禁用该插件

tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
  corePlugins: {
    opacity: false,
  }
}

最终结果是相同的,但由于许多核心插件没有提供配置,它们无论如何只能通过 corePlugins 禁用,因此最好保持一致。

🌐 The end result is the same, but since many core plugins expose no configuration they can only be disabled using corePlugins anyways, so it’s better to be consistent.


配置参考(Configuration reference)

除了 screenscolorsspacing 之外,theme 对象中的所有键都映射到 Tailwind 的 核心插件 之一。由于许多插件负责仅接受固定值集的 CSS 属性(例如 float),请注意,并非每个插件在 theme 对象中都有对应的键。

🌐 Except for screens, colors, and spacing, all of the keys in the theme object map to one of Tailwind’s core plugins. Since many plugins are responsible for CSS properties that only accept a static set of values (like float for example), note that not every plugin has a corresponding key in the theme object.

所有这些键也可以通过 theme.extend 键来使用,以启用扩展默认主题

🌐 All of these keys are also available under the theme.extend key to enable extending the default theme.

描述
accentColorValues for the accent-color property
animationValues for the animation property
ariaValues for the aria property
aspectRatioValues for the aspect-ratio property
backdropBlurValues for the backdropBlur plugin
backdropBrightnessValues for the backdropBrightness plugin
backdropContrastValues for the backdropContrast plugin
backdropGrayscaleValues for the backdropGrayscale plugin
backdropHueRotateValues for the backdropHueRotate plugin
backdropInvertValues for the backdropInvert plugin
backdropOpacityValues for the backdropOpacity plugin
backdropSaturateValues for the backdropSaturate plugin
backdropSepiaValues for the backdropSepia plugin
backgroundColorValues for the background-color property
backgroundImageValues for the background-image property
backgroundOpacityValues for the background-opacity property
backgroundPositionValues for the background-position property
backgroundSizeValues for the background-size property
blurValues for the blur plugin
borderColorValues for the border-color property
borderOpacityValues for the borderOpacity plugin
borderRadiusValues for the border-radius property
borderSpacingValues for the border-spacing property
borderWidthValues for the borderWidth plugin
boxShadowValues for the box-shadow property
boxShadowColorValues for the boxShadowColor plugin
brightnessValues for the brightness plugin
caretColorValues for the caret-color property
colorsYour project's color palette
columnsValues for the columns property
containerConfiguration for the container plugin
contentValues for the content property
contrastValues for the contrast plugin
cursorValues for the cursor property
divideColorValues for the divideColor plugin
divideOpacityValues for the divideOpacity plugin
divideWidthValues for the divideWidth plugin
dropShadowValues for the dropShadow plugin
fillValues for the fill plugin
flexValues for the flex property
flexBasisValues for the flex-basis property
flexGrowValues for the flex-grow property
flexShrinkValues for the flex-shrink property
fontFamilyValues for the font-family property
fontSizeValues for the font-size property
fontWeightValues for the font-weight property
gapValues for the gap property
gradientColorStopsValues for the gradientColorStops plugin
gradientColorStopPositionsValues for the gradient-color-stop-positions property
grayscaleValues for the grayscale plugin
gridAutoColumnsValues for the grid-auto-columns property
gridAutoRowsValues for the grid-auto-rows property
gridColumnValues for the grid-column property
gridColumnEndValues for the grid-column-end property
gridColumnStartValues for the grid-column-start property
gridRowValues for the grid-row property
gridRowEndValues for the grid-row-end property
gridRowStartValues for the grid-row-start property
gridTemplateColumnsValues for the grid-template-columns property
gridTemplateRowsValues for the grid-template-rows property
heightValues for the height property
hueRotateValues for the hueRotate plugin
insetValues for the top, right, bottom, and left properties
invertValues for the invert plugin
keyframesKeyframe values used in the animation plugin
letterSpacingValues for the letter-spacing property
lineHeightValues for the line-height property
listStyleTypeValues for the list-style-type property
listStyleImageValues for the list-style-image property
marginValues for the margin property
lineClampValues for the line-clamp property
maxHeightValues for the max-height property
maxWidthValues for the max-width property
minHeightValues for the min-height property
minWidthValues for the min-width property
objectPositionValues for the object-position property
opacityValues for the opacity property
orderValues for the order property
outlineColorValues for the outline-color property
outlineOffsetValues for the outline-offset property
outlineWidthValues for the outline-width property
paddingValues for the padding property
placeholderColorValues for the placeholderColor plugin
placeholderOpacityValues for the placeholderOpacity plugin
ringColorValues for the ringColor plugin
ringOffsetColorValues for the ringOffsetColor plugin
ringOffsetWidthValues for the ringOffsetWidth plugin
ringOpacityValues for the ringOpacity plugin
ringWidthValues for the ringWidth plugin
rotateValues for the rotate plugin
saturateValues for the saturate plugin
scaleValues for the scale plugin
screensYour project's responsive breakpoints
scrollMarginValues for the scroll-margin property
scrollPaddingValues for the scroll-padding property
sepiaValues for the sepia plugin
skewValues for the skew plugin
spaceValues for the space plugin
spacingYour project's spacing scale
strokeValues for the stroke property
strokeWidthValues for the stroke-width property
supportsValues for the supports property
dataValues for the data property
textColorValues for the color property
textDecorationColorValues for the text-decoration-color property
textDecorationThicknessValues for the text-decoration-thickness property
textIndentValues for the text-indent property
textOpacityValues for the textOpacity plugin
textUnderlineOffsetValues for the text-underline-offset property
transformOriginValues for the transform-origin property
transitionDelayValues for the transition-delay property
transitionDurationValues for the transition-duration property
transitionPropertyValues for the transition-property property
transitionTimingFunctionValues for the transition-timing-function property
translateValues for the translate plugin
sizeValues for the size property
widthValues for the width property
willChangeValues for the will-change property
zIndexValues for the z-index property