Tailwind css [3] layer & 自定義 css 樣式

Abby 旦旦
5 min readMay 23, 2022

--

使用 layer 在客製網站樣式時,寫出自定義的 css 樣式,方便管理的組件和樣版。layer 可以使用在 base、components utilities 不同區域,讓我們來看它們各自的使用方式。

@layer base
@layer base 是用來添加自定義的基本 css 樣式,例如:自定義 h1 文字大小、自定義背景顏色。

如果想自定義一個灰背景色,可以這樣寫:

#input.css
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
.bg-gray-100 {
backgroud-color: #eee;
}
}

如果想從 tailwind.config.js 檔案中的 theme 物件,取用自定義的樣式就要使用 “theme()”,如下:

#tailwind.config.js
module.exports = {
theme: {
colors:{
'blue': '#1fb6ff',
}
},
}
------------------------------------------------------------------#input.css
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
h1 {
colors: theme('colors.blue');
}
}

如果想取用 Tailwind css 預設的樣式的話,就要使用 “@apply”,如下:

#input.css
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
h2 {
@apply text-2xl;
}
}

@layer components
@layer components 是用來添加自定義的組件,例如:按鈕樣式、區塊樣式、表單樣式。

#input.css
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer components {
.card {
background-color: theme('colors.white');
border-radius: theme('borderRadius.lg');
padding: theme('spacing.6');
box-shadow: theme('boxShadow.xl');
}
.select2-dropdown {
@apply rounded-b-lg shadow-md;
}
.select2-search {
@apply border border-gray-300 rounded;
}
.select2-results__group {
@apply text-lg font-bold text-gray-900;
}
}

當然也可以使用“theme()”和“@apply”應用,是個放置客製組件的好地方。

@layer utilities
@layer utilities 是用來添加 Tailwind css 本身沒有的 css,Adding custom utilities 自定義 css 樣式,靈活運用。

使用 @layer utilities 把自定義的css寫在裡面,如下:

#input.css
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer utilities {
.content-auto {
content-visibility: auto;
}
}

使用@layer的特色

特色1:自動擁有修飾語法
任何新添加的 css 只要加在 @layer 裡面,就會自動擁有 Tailwind css 的修飾語法,例如:hover、responsive、dark mode…等,非常方便。

<div class="hover:content-auto">...</div>
<div class="lg:content-auto">...</div>
<div class="dark:content-auto">...</div>

特色2:在html中沒有使用就不會渲染
任何新添加的 css 只要加在 @layer 裡面,如果在html中沒有用使用到,就不會渲染到 output.css,方便壓縮檔案。

@tailwind base;
@tailwind components;
@tailwind utilities;
@layer components {
/* 如果樣式是空的,就不會渲染*/
.card {}
}

如果一定要渲染,就寫在 @layer 外面,如下:

@tailwind base;
@tailwind components;
@tailwind utilities;
/* 即使樣式是空的,寫在這裡一定會渲染*/
.card {}
@layer components {}

以上是 @layer 和自定義 css 樣式的初步介紹,在客製網站樣式時,尤其可以多利用這些方法,寫出方便管理的組件和樣版。

--

--

Abby 旦旦

從零開始轉職網頁設計,正在緩慢朝前端工程邁進中!偶爾會發一些讀後感和UI分享,ㄚㄚ!