Tailwind CSS - 配置



Tailwind CSS 配置允許透過定義框架的各個方面(例如主題、顏色、螢幕、外掛等)來輕鬆根據專案需求自定義框架,使用 'tailwind.config.js' 檔案。

如何生成配置檔案?

以下是生成 'tailwind.config.js' 檔案的分步指南。

  • Tailwind CSS 安裝: Tailwind CSS 的安裝是必須首先完成的步驟。執行以下命令以生成預設配置檔案
    npm install tailwindcss
  • 生成配置檔案: 使用以下命令,可以輕鬆生成 'tailwind.config.js' 檔案。
    npx tailwind css init
  • 生成的 檔案: 將生成以下檔案。
  • Tailwind CSS config.js

自定義配置

'tailwind.config.js' 檔案允許輕鬆自定義配置並將實用程式類與專案的特定設計要求對齊。我們可以輕鬆自定義主題、字型、顏色、螢幕、間距、外掛等等,如下所示。

  • 內容: 'tailwind.config.js' 檔案的內容部分使您可以新增所有 HTML 模板、JS 元件以及包含 Tailwind CSS 類的其他檔案的路徑。
  • /** @type {import('tailwindcss').Config} */
    module.exports = {
      content: [
        './pages/**/*.{html,js}',
        './components/**/*.{html,js}',
      ],
      // ...
    }
      
  • 主題: 'tailwind.config.js' 檔案的主題部分使您可以透過配置顏色、字體系列、斷點等來自定義專案的視覺設計,如下所示。
  • /** @type {import('tailwindcss').Config} */
    module.exports = {
      // ...
      theme: {
        colors: {
          'blue': '#1fb6ff',
          'purple': '#7e5bef',
          'pink': '#ff49db',
        },
        fontFamily: {
          sans: ['Graphik', 'sans-serif'],
          serif: ['Merriweather', 'serif'],
        },
        extend: {
          spacing: {
            '8xl': '96rem',
            '9xl': '128rem',
          },
        }
      }
    }
    
    ’tailwind.config.js’ 檔案的外掛部分允許您新增額外的實用程式、元件、基礎樣式、自定義變體等等,如下所示。
  • 外掛: 'tailwind.config.js' 檔案的外掛部分使您可以新增額外的實用程式、元件、基礎樣式、自定義變體等等,如下所示。
  • /** @type {import('tailwindcss').Config} */
    module.exports = {
      // ...
      plugins: [
        require('@tailwindcss/forms'),
        require('@tailwindcss/aspect-ratio'),
        require('@tailwindcss/typography'),
        require('tailwindcss-children'),
      ],
    }
    
  • 字首: 'tailwind.config.js' 檔案的字首部分允許您向所有實用程式類新增自定義字首,有助於減少命名衝突,如下所示。
  • /** @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. */
      

    在您的字首之前新增破折號修飾符以表示負值。例如,如果您的字首是 tw-,則 -mt-8 將變為 -tw-mt-8。

    <div class="-tw-mt-8">
      <!-- -->
    </div>
      

    注意: 字首僅適用於 Tailwind 生成的類,不適用於您的自定義類。要為自己的實用程式新增字首,只需將字首新增到類定義即可。

    @layer utilities {
      .tw-bg-brand-gradient { /* ... */ }
    }
      
  • 重要: important 選項允許您使用“!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. */
      

    這也適用於您使用 CSS 中的“@layer utilities”指令建立的自定義實用程式。

    /* Input */
    @layer utilities {
    .bg-brand-gradient {
    background-image: linear-gradient(#3490dc, #6574cd);
    }
    }
    
    /* Output */
    .bg-brand-gradient {
    background-image: linear-gradient(#3490dc, #6574cd) !important;
    }
      

    選擇器策略: 將 important 設定為 true 可能會與使用內聯樣式的第三方 JS 庫發生衝突,因為 Tailwind 的 '!important' 實用程式將覆蓋它們並可能破壞您的設計。

    為避免此問題,請採取以下措施

    • 將 'important' 設定為 ID 選擇器,例如 '#app'。此配置會在您的實用程式前面新增給定的選擇器,從而提高其特異性,而無需使用 '!important'。
    • /** @type {import('tailwindcss').Config} */
      module.exports = {
      // ...
      important: '#app',
      }
          
    • 為確保樣式正常工作,請為網站的根元素設定與重要選擇器相同的 ID,例如 id="app"。
    • <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>
            
    • 確保在內容配置中包含包含根選擇器的模板檔案。否則,構建生產環境時所有 CSS 都會被刪除。

    重要修飾符:您也可以透過在實用程式名稱的開頭新增“!”來使其成為重要修飾符。“!”應放在任何變體之後,但任何字首之前。當您需要更高的特異性來覆蓋其他樣式時,這很有幫助。

  • 分隔符:分隔符選項允許您選擇一個字元來分隔修飾符(如螢幕尺寸、懸停)與實用程式名稱(例如,text-center)。預設情況下,它使用冒號 (:),但您可以為不支援特殊字元的模板語言(如 Pug)更改它。
  • /** @type {import('tailwindcss').Config} */
    module.exports = {
    // ...
    important: '#app',
    }
    
    您可以使用 corePlugins 部分關閉任何不需要的預設 Tailwind 類。
  • 核心外掛:您可以使用 corePlugins 部分關閉任何不需要的預設 Tailwind 類。只需在 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 的核心外掛,只使用自定義外掛,請提供一個空陣列。

    /** @type {import('tailwindcss').Config} */
    module.exports = {
      corePlugins: []
    }
    

    以下是每個核心外掛的列表,供參考

    核心外掛 描述
    accentColor accent-color 實用程式,例如 accent-green-800
    accessibility sr-only 和 not-sr-only 實用程式
    alignContent align-content 實用程式,例如 content-between
    alignItems align-items 實用程式,例如 items-center
    alignSelf align-self 實用程式,例如 self-end
    animation animation 實用程式,例如 animate-ping
    appearance appearance 實用程式,例如 appearance-none
    aspectRatio aspect-ratio 實用程式,例如 aspect-square
    backdropBlur backdrop-blur 實用程式,例如 backdrop-blur-md
    backdropBrightness backdrop-brightness 實用程式,例如 backdrop-brightness-100
    backdropContrast backdrop-contrast 實用程式,例如 backdrop-contrast-100
    backdropFilter backdrop-filter 實用程式,例如 backdrop-filter
    backdropGrayscale backdrop-grayscale 實用程式,例如 backdrop-grayscale-0
    backdropHueRotate backdrop-hue-rotate 實用程式,例如 backdrop-hue-rotate-30
    backdropInvert backdrop-invert 實用程式,例如 backdrop-invert-0
    backdropOpacity backdrop-opacity 實用程式,例如 backdrop-opacity-50
    backdropSaturate backdrop-saturate 實用程式,例如 backdrop-saturate-100
    backdropSepia backdrop-sepia 實用程式,例如 backdrop-sepia-0
    backgroundAttachment background-attachment 實用程式,例如 bg-local
    backgroundBlendMode background-blend-mode 實用程式,例如 bg-blend-color-burn
    backgroundClip background-clip 實用程式,例如 bg-clip-padding
    backgroundColor background-color 實用程式,例如 bg-green-800
    backgroundImage background-image 實用程式,例如 bg-gradient-to-br
    backgroundOpacity background-color 透明度實用程式,例如 bg-opacity-25
    backgroundOrigin background-origin 實用程式,例如 bg-origin-padding
    backgroundPosition background-position 實用程式,例如 bg-left-top
    backgroundRepeat background-repeat 實用程式,例如 bg-repeat-x
    backgroundSize background-size 實用程式,例如 bg-cover
    blur blur 實用程式,例如 blur-md
    borderCollapse border-collapse 實用程式,例如 border-collapse
    borderColor border-color 實用程式,例如 border-e-green-800
    borderOpacity border-color 透明度實用程式,例如 border-opacity-25
    borderRadius border-radius 實用程式,例如 rounded-ss-lg
    borderSpacing border-spacing 實用程式,例如 border-spacing-x-28
    borderStyle border-style 實用程式,例如 border-dotted
    borderWidth border-width 實用程式,例如 border-e-4
    boxDecorationBreak box-decoration-break 實用程式,例如 decoration-clone
    boxShadow box-shadow 實用程式,例如 shadow-lg
    boxShadowColor box-shadow-color 實用程式,例如 shadow-green-800
    boxSizing box-sizing 實用程式,例如 box-border
    breakAfter break-after 實用程式,例如 break-after-avoid-page
    breakBefore break-before 實用程式,例如 break-before-avoid-page
    breakInside break-inside 實用程式,例如 break-inside-avoid
    brightness brightness 實用程式,例如 brightness-100
    captionSide caption-side 實用程式,例如 caption-top
    caretColor caret-color 實用程式,例如 caret-green-800
    clear clear 實用程式,例如 clear-left
    columns columns 實用程式,例如 columns-auto
    contain contain 實用程式,例如 contain-size
    container container 元件
    content content 實用程式,例如 content-none
    contrast contrast 實用程式,例如 contrast-100
    cursor cursor 實用程式,例如 cursor-grab
    display display 實用程式,例如 table-column-group
    divideColor 元素間邊框顏色實用程式,例如 divide-slate-500
    divideOpacity divide-opacity 實用程式,例如 divide-opacity-50
    divideStyle divide-style 實用程式,例如 divide-dotted
    divideWidth 元素間邊框寬度實用程式,例如 divide-x-2
    dropShadow drop-shadow 實用程式,例如 drop-shadow-lg
    fill fill 實用程式,例如 fill-green-700
    filter filter 實用程式,例如 filter
    flex flex 實用程式,例如 flex-auto
    flexBasis flex-basis 實用程式,例如 basis-px
    flexDirection flex-direction 實用程式,例如 flex-row-reverse
    flexGrow flex-grow 實用程式,例如 flex-grow
    flexShrink flex-shrink 實用程式,例如 flex-shrink
    flexWrap flex-wrap 實用程式,例如 flex-wrap-reverse
    float float 實用程式,例如 float-right
    fontFamily font-family 實用程式,例如 font-serif
    fontSize font-size 實用程式,例如 text-3xl
    fontSmoothing font-smoothing 實用程式,例如 antialiased
    fontStyle font-style 實用程式,例如 italic
    fontVariantNumeric font-variant-numeric 實用程式,例如 oldstyle-nums
    fontWeight font-weight 實用程式,例如 font-medium
    forcedColorAdjust forced-color-adjust 實用程式,例如 forced-color-adjust-auto
    gap gap 實用程式,例如 gap-x-28
    gradientColorStops gradient-color-stops 實用程式,例如 via-emerald-700
    grayscale grayscale 實用程式,例如 grayscale-0
    gridAutoColumns grid-auto-columns 實用程式,例如 auto-cols-min
    gridAutoFlow grid-auto-flow 實用程式,例如 grid-flow-dense
    gridAutoRows grid-auto-rows 實用程式,例如 auto-rows-min
    gridColumn grid-column 實用程式,例如 col-span-6
    gridColumnEnd grid-column-end 實用程式,例如 col-end-7
    gridColumnStart grid-column-start 實用程式,例如 col-start-7
    gridRow grid-row 實用程式,例如 row-span-6
    gridRowEnd grid-row-end 實用程式,例如 row-end-7
    gridRowStart grid-row-start 實用程式,例如 row-start-7
    gridTemplateColumns grid-template-columns 實用程式,例如 grid-cols-7
    gridTemplateRows grid-template-rows 實用程式,例如 grid-rows-7
    height height 實用程式,例如 h-96
    hueRotate hue-rotate 實用程式,例如 hue-rotate-30
    hyphens hyphens 實用程式,例如 hyphens-manual
    inset inset 實用程式,例如 end-44
    invert invert 實用程式,例如 invert-0
    isolation isolation 實用程式,例如 isolate
    justifyContent justify-content 實用程式,例如 justify-center
    justifyItems justify-items 實用程式,例如 justify-items-end
    justifySelf justify-self 實用程式,例如 justify-self-end
    letterSpacing letter-spacing 實用程式,例如 tracking-normal
    lineClamp line-clamp 實用程式,例如 line-clamp-4
    lineHeight line-height 實用程式,例如 leading-9
    listStyleImage list-style-image 實用程式,例如 list-image-none
    listStylePosition list-style-position 實用程式,例如 list-inside
    listStyleType list-style-type 實用程式,例如 list-disc
    margin margin 實用程式,例如 me-28
    maxHeight max-height 實用程式,例如 max-h-44
    maxWidth max-width 實用程式,例如 max-w-80
    minHeight min-height 實用程式,例如 min-h-44
    minWidth min-width 實用程式,例如 min-w-36
    mixBlendMode mix-blend-mode 實用程式,例如 mix-blend-hard-light
    objectFit object-fit 實用程式,例如 object-fill
    objectPosition object-position 實用程式,例如 object-left-top
    opacity opacity 實用程式,例如 opacity-50
    order order 實用程式,例如 order-8
    outlineColor outline-color 實用程式,例如 outline-green-800
    outlineOffset outline-offset 實用程式,例如 outline-offset-2
    outlineStyle outline-style 實用程式,例如 outline-dashed
    outlineWidth outline-width 實用程式,例如 outline-2
    overflow overflow 實用程式,例如 overflow-x-hidden
    overscrollBehavior overscroll-behavior 實用程式,例如 overscroll-y-contain
    padding padding 實用程式,例如 pe-28
    placeContent place-content 實用程式,例如 place-content-between
    placeItems place-items 實用程式,例如 place-items-center
    placeSelf place-self 實用程式,例如 place-self-end
    placeholderColor placeholder 顏色實用程式,例如 placeholder-red-600
    placeholderOpacity placeholder 顏色透明度實用程式,例如 placeholder-opacity-25
    pointerEvents pointer-events 實用程式,例如 pointer-events-none
    position position 實用程式,例如 absolute
    preflight Tailwind 的基礎/重置樣式
    resize resize 實用程式,例如 resize-y
    ringColor ring-color 實用程式,例如 ring-green-800
    ringOffsetColor ring-offset-color 實用程式,例如 ring-offset-green-800
    ringOffsetWidth ring-offset-width 實用程式,例如 ring-offset-2
    ringOpacity ring-opacity 實用程式,例如 ring-opacity-50
    ringWidth ring-width 實用程式,例如 ring-4
    rotate rotate 實用程式,例如 rotate-6
    saturate saturate 實用程式,例如 saturate-100
    scale scale 實用程式,例如 scale-x-95
    scrollBehavior scroll-behavior 實用程式,例如 scroll-auto
    scrollMargin scroll-margin 實用程式,例如 scroll-me-28
    scrollPadding scroll-padding 實用程式,例如 scroll-pe-28
    scrollSnapAlign scroll-snap-align 實用程式,例如 snap-end
    scrollSnapStop scroll-snap-stop 實用程式,例如 snap-normal
    scrollSnapType scroll-snap-type 實用程式,例如 snap-y
    sepia sepia 實用程式,例如 sepia-0
    size size 實用程式,例如 size-0.5
    skew skew 實用程式,例如 skew-x-12
    space “space-between” 實用程式,例如 space-x-4
    stroke stroke 實用程式,例如 stroke-green-700
    strokeWidth stroke-width 實用程式,例如 stroke-1
    tableLayout table-layout 實用程式,例如 table-auto
    textAlign text-align 實用程式,例如 text-right
    textColor text-color 實用程式,例如 text-green-800
    textDecoration text-decoration 實用程式,例如 overline
    textDecorationColor text-decoration-color 實用程式,例如 decoration-green-800
    textDecorationStyle text-decoration-style 實用程式,例如 decoration-dotted
    textDecorationThickness 文字裝飾粗細實用工具,例如decoration-4
    textIndent 文字縮排實用工具,例如indent-28
    textOpacity 文字透明度實用工具,例如text-opacity-50
    textOverflow 文字溢位實用工具,例如overflow-ellipsis
    textTransform 文字轉換實用工具,例如lowercase
    textUnderlineOffset 文字下劃線偏移實用工具,例如underline-offset-2
    textWrap 文字換行實用工具,例如text-nowrap
    touchAction 觸控操作實用工具,例如touch-pan-right
    transform transform實用工具(用於啟用transform特性)
    transformOrigin transform-origin實用工具,例如origin-bottom-right
    transitionDelay 過渡延遲實用工具,例如delay-200
    transitionDuration 過渡持續時間實用工具,例如duration-200
    transitionProperty 過渡屬性實用工具,例如transition-colors
    transitionTimingFunction 過渡時間函式實用工具,例如ease-in
    translate 平移實用工具,例如translate-x-full
    userSelect 使用者選擇實用工具,例如select-text
    verticalAlign 垂直對齊實用工具,例如align-bottom
    visibility 可見性實用工具,例如invisible
    whitespace 空白符實用工具,例如whitespace-pre
    width 寬度實用工具,例如w-2.5
    willChange will-change實用工具,例如will-change-scroll
    wordBreak 斷字實用工具,例如break-words
    zIndex z-index實用工具,例如z-30

設定多個配置

對於包含多個CSS檔案和不同Tailwind設定的專案,請使用@config指令為每個CSS檔案選擇配置檔案。

@config "./tailwind.site.config.js";

@tailwind base;
@tailwind components;
@tailwind utilities;

在JavaScript中管理引用

您可能需要在JavaScript程式碼中使用您的配置值,例如在向ReactVue元件新增樣式時。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)'

TypeScript型別

Tailwind CLI會自動新增型別,但如果您需要自己新增,請在您的配置上方新增一行。

/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
  // ...
],
theme: {
  extend: {},
},
plugins: [],
}
廣告