你正在瀏覽的是 Tailwind CSS v2. 的技術文件
Tailwind CSS 的 GitHub

配置 (Configuration)

設定與客製化 Tailwind 安裝的指南

因為 Tailwind 是一套建立客製化使用者介面的框架,從一開始就為了考量客製化而設計。

預設情況下,Tailwind 會在你的專案根目錄尋找可選的 tailwind.config.js 檔案,你可以在其中定義任何客製化的設定。

// `tailwind.config.js` 範例檔案
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 設定檔,當安裝 tailwindcss npm 插件包時會連同 Tailwind CLI 一起安裝。

npx tailwindcss init

上述指令將會在專案的根目錄建立一個最低限度的 tailwind.config.js 檔案。

// tailwind.config.js
module.exports = {
  purge: [],
  darkMode: false, // 或 'media' 或 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
}

使用不同的檔案名稱

如果檔案名稱不想使用 tailwind.config.js,只需要將你想的使用的名稱打在命令列 (command-line) 即可:

npx tailwindcss init tailwindcss-config.js

如果使用自定義的檔案名稱,必須要將 Tailwind 作為插件引入 PostCSS 設定檔的同時,為其指定你的檔案名稱。

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

產生 PostCSS 設定檔

使用 -p 可以讓你在 tailwind.config.js 的同一層資料夾中產生一個基本版的 postcss.config.js 檔案:

npx tailwindcss init -p

上述指令將會在你的專案中產生如同下方範例的 postcss.config.js 檔案:

module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
}

搭建完整的預設設定檔

我們鼓勵多數的使用者盡量讓設定檔保持得越小越好,並且僅寫入想客製化的部分。

如果你真的想要建構一個設定檔,其包含完整的 Tailwind 預設設定,請使用 --full 選項。

npx tailwindcss init --full

輸入上述指令將會得到一個與 Tailwind 內部使用的 預設配置檔 相同的檔案

主題

theme 區域可以讓你定義調色盤、文字、樣式量表 (type scale)、邊線尺寸、斷點…等,任何與網站上視覺設計有關的屬性。

// 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')
  ],

  // 專案特定的客製化設定
  theme: {
    //...
  },
  // ...
}

預設定文件 了解更多關於預設定。

前輟詞

prefix 選項讓你可以新增自訂的前輟詞於 Tailwind 產生的所有功能 class,當 Tailwind 和一個已存在 CSS 的出現命名衝突時,這個功能會非常有用。

例如,你可以在 prefix 選項新增 tw- 前輟詞,如下:

// tailwind.config.js
module.exports = {
  prefix: 'tw-',
}

現在每個 class 都會產生你設定的前輟詞

.tw-text-left {
  text-align: left;
}
.tw-text-center {
  text-align: center;
}
.tw-text-right {
  text-align: right;
}
/* 等等... */

請務必了解,這個自訂前輟詞是被加在任何變化模式的前輟詞 後面,這代表若 class 帶有響應式或狀態的前輟詞,像是 sm: 或是 hover:,將會 優先 將其置入於 class 前面,然後在冒號的後面才會是你自訂的前輟詞:

<div class="tw-text-lg md:tw-text-xl tw-bg-red-500 hover:tw-bg-blue-500">
  <!-- -->
</div>

前輟詞僅會新增到由 Tailwind 產生的 class;你自行新增的 class 並不會被加上前輟詞

意思是,如果你自行新增響應式功能,如下:

@variants hover {
  .bg-brand-gradient { /* ... */ }
}

…產生的響應式 class 將不會有你設定的前輟詞:

.bg-brand-gradient { /* ... */ }
.hover\:bg-brand-gradient:hover { /* ... */ }

如果你也想要在自訂的功能上產生前輟,可以直接在定義 class 時加上前輟:

@variants hover {
  .tw-bg-brand-gradient { /* ... */ }
}

Important

important 選項讓你可以自由控制是否為 Tailwind 的功能加上 !important,這對於 Tailwind 與其他權重較高的 CSS 搭配的使用情境下非常有幫助。

產生 !important 功能只需要在 important 選項設定為 true 即可:

// tailwind.config.js
module.exports = {
  important: true,
}

現在全部的 Tailwind 功能 class 將會產生 !important

.leading-none {
  line-height: 1 !important;
}
.leading-tight {
  line-height: 1.25 !important;
}
.leading-snug {
  line-height: 1.375 !important;
}
/* ...等等 */

請注意,設定此選項將不會自動為任何自定義的功能加上 !important

如果你想在你自己的功能加上 !important,只要自行在每個宣告的結尾加上 !important 即可:

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

選擇器 (Selector) 策略

important 設為 true 可能會導致一些問題,像是使用第三方 JS 插件時所新增的行內樣式,將會被 Tailwind 產生之 !important 功能因權重被壓過去,最後破壞了你預期的設計。

為了解決這個問題,你可以為一個 ID 選擇器設定 important,例如 #app

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

這個設定將會以你賦予的選擇器為功能加上前輟,可以有效的增加權重,而不需使用 !important

important 指定選擇器之後,你將需要確保該網站的根元素與其相符合,以上面為例,我們需要將根元素的 id 屬性設為 app 即可使樣式順利生效。

將根元素與你的 Tailwind 設定的選擇器設定完成後,Tailwind 的全部功能之權重將足以壓過專案中的其他 class,亦干擾其他行內樣式:

<html>
<!-- ... -->
<style>
  .high-specificity .nested .selector {
    color: blue;
  }
</style>
<body id="app">
  <div class="high-specificity">
    <div class="nested">
      <!-- 將會是 red-500 -->
      <div class="selector text-red-500"><!-- ... --></div>
    </div>
  </div>

  <!-- 將會是 #bada55 -->
  <div class="text-red-500" style="color: #bada55;"><!-- ... --></div>
</body>
</html>

When using the selector strategy, be sure that the template file that includes your root selector is included in your purge configuration, otherwise all of your CSS will be removed when building for production.

分隔符號 (Separator)

separator 選項讓你可以自訂字元或字串,它用來分隔變化模式前輟詞 (畫面尺寸、hoverfocus…等等) 與功能名稱 (text-centeritems-end…等等)。

我們預設使用分號 (:),但如果你使用模板語言時,改變其預設值將會很有幫助,例如 Pug 並不支援在 class 名稱中使用特殊符號。

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

核心插件

在你的專案裡若有任何不需要使用的 Tailwind 預設產生之 class,可以在 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 當作一個處理客製化插件的工具,請給予其空陣列。

// tailwind.config.js
module.exports = {
  corePlugins: []
}

請參考下方列出的全部核心插件:

核心插件說明
preflightTailwind 的 base/reset 樣式
containercontainer 元件
accessibilitysr-onlynot-sr-only 功能
alignContentalign-content 功能,例如: content-end
alignItemsalign-items 功能,例如: items-center
alignSelfalign-self 功能,例如: self-end
animationanimation 功能,例如:
appearanceappearance 功能,例如: appearance-none
backdropBlurbackdrop-blur 功能,例如:
backdropBrightnessbackdrop-brightness 功能,例如:
backdropContrastbackdrop-contrast 功能,例如:
backdropFilterbackdrop-filter 功能,例如: backdrop-filter
backdropGrayscalebackdrop-grayscale 功能,例如:
backdropHueRotatebackdrop-hue-rotate 功能,例如:
backdropInvertbackdrop-invert 功能,例如:
backdropOpacitybackdrop-opacity 功能,例如:
backdropSaturatebackdrop-saturate 功能,例如:
backdropSepiabackdrop-sepia 功能,例如:
backgroundAttachmentbackground-attachment 功能,例如: bg-local
backgroundBlendModebackground-blend-mode 功能,例如: bg-blend-color-burn
backgroundClipbackground-clip 功能,例如: bg-clip-padding
backgroundColorbackground-color 功能,例如:
backgroundImagebackground-image 功能,例如:
backgroundOpacitybackground-color 的透明度功能,例如: bg-opacity-25
backgroundOriginbackground-origin 功能,例如: bg-origin-padding
backgroundPositionbackground-position 功能,例如:
backgroundRepeatbackground-repeat 功能,例如: bg-repeat-x
backgroundSizebackground-size 功能,例如:
blurblur 功能,例如:
borderCollapseborder-collapse 功能,例如: border-collapse
borderColorborder-color 功能,例如:
borderOpacityborder-color 的透明度功能,例如: border-opacity-25
borderRadiusborder-radius 功能,例如:
borderStyleborder-style 功能,例如: border-dotted
borderWidthborder-width 功能,例如:
boxDecorationBreakbox-decoration-break 功能,例如: decoration-slice
boxShadowbox-shadow 功能,例如: ,
boxSizingbox-sizing 功能,例如: box-border
brightnessbrightness 功能,例如:
caretColorcaret-color 功能,例如:
clearclear 功能,例如: clear-right
contentcontent 功能,例如:
contrastcontrast 功能,例如:
cursorcursor 功能,例如:
displaydisplay 功能,例如: table-column-group
divideColor間距元素的 border-color 功能,例如: divide-gray-500
divideOpacitydivide-opacity 功能,例如:
divideStyledivide-style 功能,例如: divide-dotted
divideWidth間距元素的 border-width 功能,例如: divide-x-2
dropShadowdrop-shadow 功能,例如: drop-shadow-lg
fillfill 功能,例如:
filterfilter 功能,例如: filter
flexflex 功能,例如:
flexDirectionflex-direction 功能,例如: flex-row-reverse
flexGrowflex-grow 功能,例如:
flexShrinkflex-shrink 功能,例如:
flexWrapflex-wrap 功能,例如: flex-wrap-reverse
floatfloat 功能,例如: float-left
fontFamilyfont-family 功能,例如:
fontSizefont-size 功能,例如:
fontSmoothingfont-smoothing 功能,例如: antialiased
fontStylefont-style 功能,例如: italic
fontVariantNumericfont-variant-numeric 功能,例如: lining-nums
fontWeightfont-weight 功能,例如:
gapgap 功能,例如:
gradientColorStopsgradient-color-stops 功能,例如:
grayscalegrayscale 功能,例如:
gridAutoColumnsgrid-auto-columns 功能,例如:
gridAutoFlowgrid-auto-flow 功能,例如: grid-flow-col
gridAutoRowsgrid-auto-rows 功能,例如:
gridColumngrid-column 功能,例如:
gridColumnEndgrid-column-end 功能,例如:
gridColumnStartgrid-column-start 功能,例如:
gridRowgrid-row 功能,例如:
gridRowEndgrid-row-end 功能,例如:
gridRowStartgrid-row-start 功能,例如:
gridTemplateColumnsgrid-template-columns 功能,例如:
gridTemplateRowsgrid-template-rows 功能,例如:
heightheight 功能,例如:
hueRotatehue-rotate 功能,例如:
insetinset 功能,例如:
invertinvert 功能,例如:
isolationisolation 功能,例如: isolate
justifyContentjustify-content 功能,例如: justify-center
justifyItemsjustify-items 功能,例如: justify-items-end
justifySelfjustify-self 功能,例如: justify-self-end
letterSpacingletter-spacing 功能,例如:
lineHeightline-height 功能,例如:
listStylePositionlist-style-position 功能,例如: list-inside
listStyleTypelist-style-type 功能,例如:
marginmargin 功能,例如:
maxHeightmax-height 功能,例如:
maxWidthmax-width 功能,例如:
minHeightmin-height 功能,例如:
minWidthmin-width 功能,例如:
mixBlendModemix-blend-mode 功能,例如: mix-blend-color-burn
objectFitobject-fit 功能,例如: object-fill
objectPositionobject-position 功能,例如:
opacityopacity 功能,例如:
orderorder 功能,例如:
outlineoutline 功能,例如:
overflowoverflow 功能,例如: overflow-y-auto
overscrollBehavioroverscroll-behavior 功能,例如: overscroll-y-contain
paddingpadding 功能,例如:
placeContentplace-content 功能,例如: place-content-between
placeholderColorplaceholder color 功能,例如: placeholder-red-600
placeholderOpacityplaceholder color 的透明度功能,例如: placeholder-opacity-25
placeItemsplace-items 功能,例如: place-items-end
placeSelfplace-self 功能,例如: place-self-end
pointerEventspointer-events 功能,例如: pointer-events-none
positionposition 功能,例如: absolute
resizeresize 功能,例如: resize-y
ringColorring-color 功能,例如:
ringOffsetColorring-offset-color 功能,例如:
ringOffsetWidthring-offset-width 功能,例如:
ringOpacityring-opacity 功能,例如:
ringWidthring-width 功能,例如: ,
rotaterotate 功能,例如:
saturatesaturate 功能,例如:
scalescale 功能,例如:
sepiasepia 功能,例如:
skewskew 功能,例如:
space"space-between" 功能,例如: space-x-4
strokestroke 功能,例如:
strokeWidthstroke-width 功能,例如:
tableLayouttable-layout 功能,例如: table-auto
textAligntext-align 功能,例如: text-center
textColortext-color 功能,例如:
textDecorationtext-decoration 功能,例如: line-through
textOpacitytext-opacity 功能,例如:
textOverflowtext-overflow 功能,例如: overflow-ellipsis
textTransformtext-transform 功能,例如: lowercase
transformtransform 功能 (用來啟用 transform 功能)
transformOrigintransform-origin 功能,例如:
transitionDelaytransition-delay 功能,例如:
transitionDurationtransition-duration 功能,例如:
transitionPropertytransition-property 功能,例如:
transitionTimingFunctiontransition-timing-function 功能,例如:
translatetranslate 功能,例如:
userSelectuser-select 功能,例如: select-text
verticalAlignvertical-align 功能,例如: align-middle
visibilityvisibility 功能,例如: visible
whitespacewhitespace 功能,例如: whitespace-pre
widthwidth 功能,例如:
wordBreakword-break 功能,例如: break-words
zIndexz-index 功能,例如:

在 JavaScript 中引用

在用戶端的 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,它可以在建構時產生靜態版本的配置檔。