Tailwind CSS on GitHub

配置

关于配置和自定义安装的指南。

因为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'],
    }
  }
}

配置文件里面的所有字段都是可选的,你可以只定制你需要修改的部分,剩余的会使用默认配置.

Creating your configuration file

当你安装好了tailwindcss依赖包,就可以使用Tailwind CLI生成一个基础配置文件:

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配置文件中显性标明:

// postcss.config.js
module.exports = {
  plugins: {
    tailwindcss: { config: './tailwindcss-config.js' },
  },
}

生成一个PostCSS配置文件

使用-p选项可以再生成一个PostCSS配置文件,名字为postcss.config.js

npx tailwindcss init -p

这会生成一个PostCSS配置文件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. */

需要注意的是,这个前缀是在变体之后的。

<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

important可以让你控制哪些类可以带有!important,当你把Tailwind跟其他CSS类一起使用的时候,这可以让Tailwind保持更高的权限:

想要生成!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,手动加上即可:

@responsive {
  .bg-brand-gradient {
    background-image: linear-gradient(#3490dc, #6574cd) !important;
  }
}

选择器策略

important设置为true,当使用第三发JS库向你的标签添加内联样式的时候,可能会引发一些问题。因为Tailwind的!important工具类权限比内联样式更高,这可能会出现预期之外的结果。

要解决这个问题,你可以设置important为一个ID选择器,如#app

// tailwind.config.js
module.exports = {
  important: '#app',
}

这样配置,可以让所有Tailwind生成的工具类都基于这个前缀选择器,这样有效的增加了权重,而不需要添加!important

当你将important设置为一个选择器,你要确保它是你的站点的根节点,为了让上面的例子可以工作,我们需要将根节点的id设置为app

当你配置好之后,你的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配置项可以让你自定义一个字符或者字符串来分隔不同的前缀(screen, 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可以让你完全禁用一些你不需要的类。

如果你不设置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.config.js
module.exports = {
  corePlugins: []
}

核心插件参考:

Core PluginDescription
preflightTailwind's base/reset styles
containerThe container component
accessibilityThe sr-only and not-sr-only utilities
alignContentThe align-content utilities like content-end
alignItemsThe align-items utilities like items-center
alignSelfThe align-self utilities like self-end
animationThe animation utilities like animate-none
appearanceThe appearance utilities like appearance-none
backgroundAttachmentThe background-attachment utilities like bg-local
backgroundClipThe background-clip utilities like bg-clip-padding
backgroundColorThe background-color utilities like bg-green-700
backgroundImageThe background-image utilities like bg-gradient-to-br
backgroundOpacityThe background-color opacity utilities like bg-opacity-25
backgroundPositionThe background-position utilities like bg-left-top
backgroundRepeatThe background-repeat utilities like bg-repeat-x
backgroundSizeThe background-size utilities like bg-cover
borderCollapseThe border-collapse utilities like border-collapse
borderColorThe border-color utilities like border-green-700
borderOpacityThe border-color opacity utilities like border-opacity-25
borderRadiusThe border-radius utilities like rounded-l-3xl
borderStyleThe border-style utilities like border-dotted
borderWidthThe border-width utilities like border-l-2
boxShadowThe box-shadow utilities like shadow-lg
boxSizingThe box-sizing utilities like box-border
clearThe clear utilities like clear-right
cursorThe cursor utilities like cursor-wait
displayThe display utilities like table-column-group
divideColorThe between elements border-color utilities like divide-gray-500
divideOpacityThe divide-opacity utilities like divide-opacity-50
divideStyleThe divide-style utilities like divide-dotted
divideWidthThe between elements border-width utilities like divide-x-2
fillThe fill utilities like fill-current
flexThe flex utilities like flex-auto
flexDirectionThe flex-direction utilities like flex-row-reverse
flexGrowThe flex-grow utilities like flex-grow-0
flexShrinkThe flex-shrink utilities like flex-shrink-0
flexWrapThe flex-wrap utilities like flex-wrap-reverse
floatThe float utilities like float-left
fontFamilyThe font-family utilities like font-serif
fontSizeThe font-size utilities like text-3xl
fontSmoothingThe font-smoothing utilities like antialiased
fontStyleThe font-style utilities like italic
fontVariantNumericThe font-variant-numeric utilities like lining-nums
fontWeightThe font-weight utilities like font-medium
gapThe gap utilities like gap-x-28
gradientColorStopsThe gradient-color-stops utilities like via-green-700
gridAutoColumnsThe grid-auto-columns utilities like auto-cols-min
gridAutoFlowThe grid-auto-flow utilities like grid-flow-col
gridAutoRowsThe grid-auto-rows utilities like auto-rows-min
gridColumnThe grid-column utilities like col-span-6
gridColumnEndThe grid-column-end utilities like col-end-7
gridColumnStartThe grid-column-start utilities like col-start-7
gridRowThe grid-row utilities like row-span-3
gridRowEndThe grid-row-end utilities like row-end-4
gridRowStartThe grid-row-start utilities like row-start-4
gridTemplateColumnsThe grid-template-columns utilities like grid-cols-7
gridTemplateRowsThe grid-template-rows utilities like grid-rows-4
heightThe height utilities like h-64
insetThe inset utilities like bottom-10
justifyContentThe justify-content utilities like justify-center
justifyItemsThe justify-items utilities like justify-items-end
justifySelfThe justify-self utilities like justify-self-end
letterSpacingThe letter-spacing utilities like tracking-normal
lineHeightThe line-height utilities like leading-9
listStylePositionThe list-style-position utilities like list-inside
listStyleTypeThe list-style-type utilities like list-disc
marginThe margin utilities like ml-8
maxHeightThe max-height utilities like max-h-32
maxWidthThe max-width utilities like max-w-5xl
minHeightThe min-height utilities like min-h-full
minWidthThe min-width utilities like min-w-full
objectFitThe object-fit utilities like object-fill
objectPositionThe object-position utilities like object-left-top
opacityThe opacity utilities like opacity-50
orderThe order utilities like order-8
outlineThe outline utilities like outline-white
overflowThe overflow utilities like overflow-y-auto
overscrollBehaviorThe overscroll-behavior utilities like overscroll-y-contain
paddingThe padding utilities like pr-4
placeContentThe place-content utilities like place-content-between
placeholderColorThe placeholder color utilities like placeholder-red-600
placeholderOpacityThe placeholder color opacity utilities like placeholder-opacity-25
placeItemsThe place-items utilities like place-items-end
placeSelfThe place-self utilities like place-self-end
pointerEventsThe pointer-events utilities like pointer-events-none
positionThe position utilities like absolute
resizeThe resize utilities like resize-y
ringColorThe ring-color utilities like ring-green-700
ringOffsetColorThe ring-offset-color utilities like ring-offset-green-700
ringOffsetWidthThe ring-offset-width utilities like ring-offset-2
ringOpacityThe ring-opacity utilities like ring-opacity-50
ringWidthThe ring-width utilities like ring-2
rotateThe rotate utilities like rotate-180
scaleThe scale utilities like scale-x-95
skewThe skew utilities like -skew-x-1
spaceThe "space-between" utilities like space-x-4
strokeThe stroke utilities like stroke-current
strokeWidthThe stroke-width utilities like stroke-1
tableLayoutThe table-layout utilities like table-auto
textAlignThe text-align utilities like text-center
textColorThe text-color utilities like text-green-700
textDecorationThe text-decoration utilities like line-through
textOpacityThe text-opacity utilities like text-opacity-50
textOverflowThe text-overflow utilities like overflow-ellipsis
textTransformThe text-transform utilities like lowercase
transformThe transform utility (for enabling transform features)
transformOriginThe transform-origin utilities like origin-bottom-right
transitionDelayThe transition-delay utilities like delay-200
transitionDurationThe transition-duration utilities like duration-200
transitionPropertyThe transition-property utilities like transition-colors
transitionTimingFunctionThe transition-timing-function utilities like ease-in
translateThe translate utilities like -translate-x-full
userSelectThe user-select utilities like select-text
verticalAlignThe vertical-align utilities like align-middle
visibilityThe visibility utilities like visible
whitespaceThe whitespace utilities like whitespace-pre
widthThe width utilities like w-0.5
wordBreakThe word-break utilities like break-words
zIndexThe z-index utilities like z-30

在JS中引用

在客户端的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这样的工具,在构建时生成配置的静态版本。