iT邦幫忙

0

CSS - Tailwind CSS 阿哩阿雜的設定

Ares 2021-01-04 11:59:406134 瀏覽

上一篇介紹了 Tailwind 基本的語法,而今天要來看的是 Tailwind 的設定,之前說到的許多功能都是靠著這些設定達成,包含變數、模組化、tree-shake 等等,那就廢話不多說一起來看看設定吧~GOGO!

CSS - Tailwind CSS 入門與語法

設定檔

上次我們說到的 tailwind.config.js 這個檔案包含了各種相關設定,可以使用以下指令產生設定檔

<!-- 建立設定檔 -->
$ npx tailwindcss init
<!-- 建立包含所有預設值的設定檔 -->
$ npx tailwindcss init --full
<!-- 建立設定檔與 postcss.config.js -->
$ npx tailwindcss init -p

產出的設定檔包含幾個常用設定,如下

// tailwind.config.js

module.exports = {
  purge: [],
  darkMode: false,
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
  
  // 預設沒顯示但可使用的設定
  // prefix: '',
  // important: false,
  // separator: ':',
  // presets: [],
  // variantOrder: [],
  // corePlugins: [],
}

postcss.config.js

上面其中一個指令會生成 postcss.config.js,這個檔案是用來載入 postcss 插件用的,這邊預設會載入 tailwindcssautoprefixer,如果想要載入其他的插件或設定才會用到這個檔案

// postcss.config.js

module.exports = {
  plugins: {
    // 使用 ./config.js 當作 Tailwind 的設定檔
    tailwindcss: { config: './config.js' },
    autoprefixer: {},
  },
}

presets

presets 可使用其他預設值替換 Tailwind 的預設值,如果團隊內有自己常用的預設值就可以使用此功能,設定一次之後開新專案時就可以節省許多時間,詳細設定方式可以參考官方

// tailwind.config.js

module.exports = {
  presets: [
    require('@acmecorp/tailwind-base')
  ]
}
  • 若設定重複,最後一個將蓋過前面的設定
  • 若設定檔有以下設定會進行完全覆蓋,其餘則是採用合併方式
    • purge
    • darkMode
    • prefix
    • important
    • variantOrder
    • separator

prefix

prefix 會將撰寫的 class 加上自定義的前綴,可防止樣式的衝突,在撰寫插件時常會使用到該功能

// tailwind.config.js

module.exports = {
  prefix: 'tw-'
}
.tw-text-left {
  text-align: left;
}
  • prefix 對自定義的 class 無效

important

important 控制 css 後方是否加入 !important

// tailwind.config.js

module.exports = {
  important: true
}
.text-left {
  text-align: left !important;
}
  • important 對自定義的 class 無效

因為 !important 有可能會導致 inline style 無效,或者引發其他權重問題,所以這邊 important 也可設定一個 IDclass,編譯時 Tailwind 會加入該選擇器前綴,而不是加上 !important

// tailwind.config.js

module.exports = {
  important: '#app'
}
#app .text-left {
  text-align: left;
}

separator

separator 可自定義 RWD、hover 等等的區隔符號,預設為 :

// tailwind.config.js

module.exports = {
  separator: '_'
}
/* 預設為 ':' */
.sm:bg-fixed {
  background-attachment: fixed;
}
/* 修改為 '_' */
.sm_bg-fixed {
  background-attachment: fixed;
}

purge

purge 為 tree-shake 的功能,它會使用正則表達式偵測樣版,並將沒有用到的 class 刪除

// tailwind.config.js

module.exports = {
  purge: ['./**/*.html']
}

以上設定會在環境變數為 production 時執行,如果專案沒有用到 webpack 的話,也可以用以下方式設定

// tailwind.config.js

module.exports = {
  purge: {
    layers: ['utilities'], // 指定清除樣式的圖層
    mode: 'all', // 刪除選定圖層未使用的樣式
    preserveHtmlElements: false, // 清除沒用到的 html 元素設定
    enabled: true, // 是否開啟 purge
    content: ['./**/*.html'], // 偵測哪些樣版內容
    options: {
      safelist: ['bg-red-500', 'px-4'] // 不會被清除的樣式
    }
  }
}
  • 不要使用字串拼接 class,以防正則表達式偵測不到
  • purge 僅會清除 layers 內未使用的樣式
  • layers 預設為 basecomponentsutilities
  • preserveHtmlElements 的 html 元素指的是 h1body 等等的樣式
  • 官方不推薦使用 preserveHtmlElementsmode

darkMode

darkMode 為深色模式,有 falsemediaclass 三個選項,開啟後 dark 前綴的 class 優先度會大於一般 class

  • false:關閉深色模式
  • media:依照裝置的 prefers-color-scheme 開啟深色模式
  • class:手動設定深色模式,依照根目錄的 <html> 是否有 class="dark" 切換
<!-- 關閉深色模式 -->
<html>
<head></head>
<body>
  <div class="bg-white dark:bg-black"></div>
</body>
</html>

<!-- 開啟深色模式 -->
<html class="dark">
<head></head>
<body>
  <div class="bg-white dark:bg-black"></div>
</body>
</html>

theme

theme 即是變數的概念,所有的斷點、顏色、間距等等皆會在這邊做設定

extend

extend 會繼承預設值,並新增變數或覆蓋舊有變數

// tailwind.config.js

module.exports = {
  theme: {
    // 覆蓋 colors 預設值,僅留下 black
    colors: {
      black: '#333'
    },
    extend: {
      // 保留 colors 預設值,並覆蓋 black
      colors: {
        black: '#444'
      }
    }
  }
}
  • 優先順序為: extend > theme > 預設值

theme()

Tailwind 提供了 theme() 來幫我們減少重複作業,在上一篇我們也有提到過,使用方式如下

// tailwind.config.js

module.exports = {
  theme: {
    colors: {
      black: '#333'
    },
    // 這邊 theme 的回傳值等於前面 colors 的值
    backgroundColor: theme => theme('colors')
  }
}

擴充預設樣式

如果想要擴充預設的樣式又不想重寫預設值,則可以先載入預設樣式再合併

// tailwind.config.js

const defaultTheme = require('tailwindcss/defaultTheme')
module.exports = {
  theme: {
    extend: {
      fontFamily: {
        sans: [
          'Lato',
          ...defaultTheme.fontFamily.sans
        ]
      }
    }
  }
}

另外說一下官方這邊提供了三個東西可載入

// 預設顏色
const defaultTheme = require('tailwindcss/colors')
// 預設設定
const defaultTheme = require('tailwindcss/defaultConfig')
// 預設 theme
const defaultTheme = require('tailwindcss/defaultTheme')

variants

variants 可以設定 theme 內的樣式或是插件支援哪寫變化,例如 RWD 斷點、深色模式、hover 等等

extend

功能同 theme 的 extend,會繼承預設值,並新增設定

// tailwind.config.js

module.exports = {
  variants: {
    // 覆蓋 backgroundColor 預設值,僅留下 responsive
    backgroundColor: ['responsive']
    extend: {
      // 保留 backgroundColor 預設值,並新增 active
      backgroundColor: ['active']
    }
  }
}

優先權

編譯 variants 內的項目時,會由陣列第一個開始編譯,也就是說最後一個 variant 優先權最高,所以如果要調整優先權請依照自己需求排序,另外還可以使用 DEFAULT 來表示普通 class 的位置

// tailwind.config.js

module.exports = {
  variants: {
    // 這邊以 bg-white 為例,優先權如下
    // .hover:bg-white < bg-white < .focus:bg-white
    backgroundColor: ['hover', 'DEFAULT', 'focus']
  }
}

variantOrder

上面有提到 variants 優先權的部分,如果有在 extend 用到的屬性,不管前面如何設定,它都會照著預設優先權去編譯,並將新增的放到最後方,這時候如果想修改就必須設定 variantOrder

// tailwind.config.js

module.exports = {
  // 這邊以 bg-white 為例,設定 variantOrder 後優先權如下
  // bg-white < .focus:bg-white < .hover:bg-white < .active:bg-white
  variantOrder: [
    'DEFAULT',
    'focus',
    'hover',
    'active'
  ],
  variants: {
    backgroundColor: ['hover', 'DEFAULT', 'focus'],
    extend: {
      // 這邊以 bg-white 為例,沒有設定 variantOrder 優先權如下
      // bg-white < .hover:bg-white < .focus:bg-white < .active:bg-white
      backgroundColor: ['active']
    }
  }
}

corePlugins

corePlugins 可以禁用某些你不需要的樣式,有物件型與陣列型,詳細選項可參考官方

// tailwind.config.js

module.exports = {
  // 使用物件 true 與 false 決定使否啟用樣式
  corePlugins: {
    float: false,
    objectFit: false,
    objectPosition: false,
  },
  
  // 啟用陣列內所有樣式
  corePlugins: [
    'margin',
    'padding',
    'backgroundColor'
  ],
  
  // 禁用所有樣式
  corePlugins: []
}

plugins

plugins 是 Tailwind 一個重要的功能,它提供開發者自行開發插件,或是載入別人寫好的插件

載入插件

以下載入他人的插件,並新增一個 group-disabledvariants

// tailwind.config.js

module.exports = {
  variantOrder: [
    'hover',
    'group-disabled'
  ],
  variants: {
    extend: {
      backgroundColor: ['group-disabled']
    }
  },
  plugins: [
    require('tailwindcss-interaction-variants')
  ]
}

撰寫插件

首先要載入 plugin 函式,並依照官方格式撰寫,這邊加入兩個 class 而且設定 variants

// tailwind.config.js

const plugin = require('tailwindcss/plugin')
module.exports = {
  prefix: 'tw-',
  important: true,
  variants: {
    customPlugin: ['responsive', 'hover'],
  },
  plugins: [
    plugin(function({ addUtilities, variants }) {
      const newUtilities = {
        '.skew-10deg': { transform: 'skewY(-10deg)' },
        '.skew-15deg': { transform: 'skewY(-15deg)' }
      }
      
      addUtilities(newUtilities, {
        // 是否依照依照設定檔加上前綴,預設為 true
        respectPrefix: true,
        // 是否依照設定檔加上 !important,預設為 true
        respectImportant: true,
        // 依照設定檔加入 variant
        variants: variants('customPlugin')
      })
    })
  ]
}

這邊插件的撰寫有太多的變化,可以撰寫 baseutilitiecomponent 等等,自由度相當高,所以這邊就不多做琢磨了

結語

看完 Tailwind 的設定其實並不難,許多東西預設值就很夠了,而且針對需要的地方客製化也相當方便,除此之外還有許多 plugin 可供使用,這也是它優秀的地方之一,畢竟有社群與自己的生態系在就會持續的進步,相信 Tailwind 未來會被更廣泛的使用


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言