Tailwind CSS - 新增自定義樣式


在 Tailwind CSS 中,**新增自定義樣式** 意味著向框架新增您自己獨特的樣式。

通常,任何框架的挑戰在於知道在它沒有提供您需要的所有內容時該怎麼做。Tailwind 的設計靈活且可定製,因此您可以根據專案進行調整。

我們將指導您調整設計設定、**新增自定義 CSS** 和使用**外掛**來改進 Tailwind 的功能。

自定義您的 Tailwind 主題

要自定義 Tailwind CSS 中的字型大小、邊框樣式或間距等內容,您需要在**tailwind.config.js**檔案中進行更新。方法如下:

將您的自定義設定新增到**tailwind.config.js**檔案。例如,您可以透過這種方式調整字型大小並引入新的邊框樣式。

示例

 
/** @type {import('tailwindcss').Config} */
module.exports = {
    theme: {
        fontSize: {
          'xs': '0.75rem',
          'sm': '0.875rem',
          'base': '1rem',
          'lg': '1.125rem',
          'xl': '1.25rem',
          '2xl': '1.5rem',
          '3xl': '1.875rem',
          '4xl': '2.25rem',
          '5xl': '3rem',
        },
        borderColor: {
          'primary': '#4a90e2',
          'secondary': '#d0021b',
          'tertiary': '#f5a623',
        },
        extend: {
          spacing: {
            'extra-wide': '40rem',
          },
          borderRadius: {
            'extra-large': '1.5rem',
          },
        },
    },
}

使用**更新後的配置**,您現在可以在 HTML 中使用自定義的**字型大小**和**邊框樣式**。以下是應用它們的方法。

示例

<div class="p-extra-wide border-primary border-2 
            rounded-extra-large text-3xl">
        This is a styled div with custom spacing, 
        border color, and font size.
</div>     

有關**自定義**主題的更多詳細資訊,請檢視**主題配置文件**。

Tailwind CSS 中的任意值

在**Tailwind CSS**中,您通常使用預定義的設計設定來設定元素樣式。但是,當您需要更精確地控制設計時,Tailwind 允許您使用**任意值**。

有時,您的設計需求可能不符合**Tailwind 的預設**選項。例如,您可能需要一個在**標準配置**中不可用的獨特邊框寬度或填充。**任意值**允許您直接在類名中設定這些自定義大小,從而獲得您想要的確切外觀。

要在 Tailwind CSS 中應用**任意值**,請使用**方括號**表示法。這允許您將任何有效的 CSS 值直接插入到類名中。

示例

<!DOCTYPE html>
<html lang="en">
<head> 
    <script src="https://cdn.tailwindcss.com"></script>
</head>

<body class="p-4">
    <div class="border-[5px] p-[30px] bg-gray-300 rounded-lg shadow-lg">
        <h2 class="text-2xl font-bold mb-4 text-gray-800">Card Title</h2>
            This is an example card with custom border width and padding.
            The background color is a light gray, and additional 
            styling includes rounded corners and a shadow effect.
    </div>
</body>

</html>

在此示例中,**border-[5px]** 將邊框寬度設定為 5 畫素,而**p-[30px]** 將所有側面的填充增加 30 畫素,顯示了**任意值**的使用。

您可以使用諸如間距和定位之類的**任意值**。以下是如何使用特定值定位元素並使其具有響應性的示例。

示例

<div class="top-[117px] lg:top-[344px]">
      <!-- Your content here -->
</div>

此處,**top-[117px]** 將位置設定為距頂部 117 畫素,而**lg:top-[344px]** 在大螢幕上將其移動到距頂部 344 畫素。

**任意值**也可用於背景顏色、字型大小和偽元素。

示例

<div class="bg-[#bada55] text-[22px] before:content-['Festivus']">
    <!-- Your content here -->
</div>

此處,**bg-[#bada55]** 更改背景顏色,**text-[22px]** 設定字型大小,而**before:content-['Festivus']** 在內容前新增“**Festivus**”。

您可以引用來自您的**Tailwind 配置**檔案的 design tokens 以實現一致的樣式。

示例

<div class="grid grid-cols-[fit-content(theme(spacing.32))]">
    <!-- Your content here -->
</div> 

此處,theme **(spacing.32)** 從您的**tailwind.config.js**中獲取間距值。

如果您為專案定義了 CSS 變數,則可以像這樣直接使用它們

示例

<div class="bg-[--my-color]">
    <!-- Your content here -->
</div>

在這種情況下,**--my-color** 是在樣式表其他位置定義的 CSS 變數。

任意屬性

Tailwind CSS 中的**任意屬性**允許您使用方括號直接在實用程式類中使用自定義 CSS 值。

有時,您可能需要一個未包含在**Tailwind 實用程式**中的 CSS 屬性。例如,如果您需要一個預設情況下不可用的特定**backdrop-filter**效果,則可以使用**任意值**。

示例

<div class="blurred-bg [backdrop-filter:blur(10px)]">
    <!-- Content with a blurred backdrop effect -->
</div>

您還可以使用**Tailwind CSS**任意值來使用修飾符動態設定樣式。例如,調整元素在**懸停**時的**backdrop-filter**。

示例

<div class="blurred-bg [backdrop-filter:blur(10px)] hover:[backdrop-filter:blur(20px)]">
    <!-- Content with a blurred backdrop effect -->
</div>

**Tailwind CSS**的任意值可用於根據螢幕大小等條件調整 CSS 變數。例如,使用在不同螢幕尺寸下變化的 CSS 變數設定填充

示例

<div class="dynamic-padding [--padding-size:20px] 
            md:[--padding-size:40px] lg:[--padding-size:60px]">
    <!-- Content with padding based on screen size -->
</div>

Tailwind CSS 中的任意變體

Tailwind CSS 中的**任意變體**使您可以直接在 HTML 中應用自定義樣式。與**hover:** 或**md:** 等預定義變體不同,您可以使用**方括號**當場建立新的變體。

示例

<!DOCTYPE html>
<html lang="en">
<head> 
    <script src="https://cdn.tailwindcss.com"></script>
</head>

<body class="p-4">
    <button class="bg-blue-500 text-white p-4 rounded 
                   hover:[background-color:#46b789]">
              Hover Over Me
    </button>
</body>

</html>

檢視**任意變體文件**以瞭解更多詳細資訊。

處理空白字元

在Tailwind CSS中處理空白字元意味著使用下劃線(_)代替任意值中的空格,Tailwind會在構建時將其轉換為空格。

示例

<!DOCTYPE html>
<html lang="en">
<head> 
    <script src="https://cdn.tailwindcss.com"></script> 
</head>

<body class="p-6"> 
    <div class="text-[line-height:2rem]">
        This text has a line height of 2rem.
    </div>
</body>

</html>

當您需要在不允許使用空格的URL或路徑中包含空格時,請使用下劃線(_)。例如,Tailwind CSS會保留下劃線,不會將其轉換為空格。

示例

<div class="bg-[url('/hello_to_world.png')]....">
    <!-- Example of using underscores in URLs -->
</div>

當您需要下劃線但空格也有效時,請使用反斜槓(\)轉義下劃線,Tailwind會將其保留為下劃線。

示例

<div class="text-[letter-spacing:\0.1em]">
    <!-- -->
</div>

在JSX中,由於反斜槓通常被視為跳脫字元,請使用String.raw()以確保反斜槓被正確包含在輸出HTML中。

示例

<div className={String.raw`before:content-['Welcome\_to our Website']`}>
    <!-- ... -->
</div>

解決歧義

在Tailwind中,一些實用程式類具有相似的名稱,但應用於不同的CSS屬性。例如,border-4設定邊框寬度,而border-red-800將邊框顏色更改為紅色。即使兩者都以border開頭,它們也處理邊框樣式的不同部分。

當您使用自定義值時,Tailwind會根據您提供的值自動理解要應用哪個屬性。

示例

<!DOCTYPE html>
<html lang="en">
<head> 
    <script src="https://cdn.tailwindcss.com"></script> 
</head>  

<body class="p-6"> 
      <div class="text-[22px]">
          This text has a font size of 22px.
      </div> 
      <div class="text-[#67aa55]">
          This text has a color defined by a hex code.
      </div>
</body>

</html>

歧義可能發生在CSS變數中。例如,如果您使用text-[var(--my-var)],Tailwind無法判斷--my-var是字型大小還是顏色。

假設您有一個用於大小或顏色的CSS變數,如下所示。

示例

<div class="text-[var(--my-value)]">
    This text uses a CSS variable.
</div>

在此示例中,--my-value可用於各種目的,例如字型大小或顏色。

為了闡明應如何使用var(--my-value),您可以顯式指定型別。這有助於Tailwind準確理解如何應用CSS變數。

如果--my-value意在作為字型大小,或者--my-value意在作為顏色,則應按此方式使用它。

示例

<!-- Font size using CSS variable -->
<div class="text-[length:var(--font-size)]">
    This text uses a CSS variable for font size.
</div>

<!-- Color using CSS variable -->
<div class="text-[color:var(--text-color)]">
    This text uses a CSS variable for color.
</div>

使用CSS和@layer

使用Tailwind CSS時,您可能需要其實用程式未涵蓋的自定義樣式。使用@layer指令將這些樣式新增到Tailwind的系統中,以進行正確的排序和最佳化。

對於簡單的自定義CSS,您可以直接將其新增到樣式表中。

示例

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

.custom-button {
    background-color: #4a90e2; /* Custom background color */
    border-radius: 12px;      /* Custom border radius */
    color: white;              /* Custom text color */
    padding: 10px 20px;        /* Custom padding */
    text-align: center;        /* Center text */
}

為了獲得更多控制,可以使用@layer指令將自定義樣式新增到Tailwind的base、componentsutilities層。這有助於您的樣式與Tailwind的現有系統很好地融合。

示例

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

@layer components {
    .custom-button {
        background-color: #4a90e2; /* Custom background color */
        border-radius: 12px;      /* Custom border radius */
        color: white;              /* Custom text color */
        padding: 10px 20px;        /* Custom padding */
        text-align: center;        /* Center text */
        box-shadow: 0 4px 8px rgba(0,0,0,0.2); /* Custom shadow */
        font-size: 16px;           /* Custom font size */
    }
}

為什麼Tailwind將樣式分組到不同的層?

Tailwind將樣式分組到不同的層中,以管理它們如何互動以及哪個樣式具有優先順序。這種方法有助於防止衝突,並確保樣式以一致且有序的方式應用。

示例

.header {
    font-size: 20px;
    
    }
    
.text-large {
    font-size: 24px;
    
    }

如果同時使用這兩種樣式。

示例

<h1 class="header text-large">Hello World</h1>

文字將為24px,因為.text-large.header之後,因此它具有優先順序。

Tailwind將樣式組織到三個層

  • 基礎層 (Base Layer): 應用設定基本外觀和感覺的預設樣式,例如字型和顏色。
  • 元件層 (Components Layer): 為特定元素(例如按鈕)新增樣式,您可以輕鬆重複使用這些樣式。
  • 實用程式層 (Utilities Layer): 包含小的、單一用途的樣式,可以覆蓋其他層中的任何內容,以進行精確的設計更改。

明確樣式的互動方式使它們更容易管理。@layer指令幫助您控制樣式的最終順序,同時允許您根據需要組織程式碼。

Tailwind CSS中的@layer指令允許您將自定義樣式新增到Tailwind的現有層中。它使您的樣式井然有序,與Tailwind的實用程式配合良好,並支援諸如修飾符tree-shaking等功能,從而提高效能。

在Tailwind CSS中新增基礎樣式

要在Tailwind CSS中為頁面設定預設樣式(例如文字顏色或背景顏色),只需直接在您的<html>或<body>元素中新增類。

示例

<!DOCTYPE html>
<html lang="en">
<head> 
    <script src="https://cdn.tailwindcss.com"></script> 
</head> 

<body class="p-6">
    <header class="bg-blue-500 text-white p-4 rounded">
        <h1 class="text-3xl font-semibold">My Website</h1>
    </header>
    <main class="mt-6">
        <h2 class="text-2xl font-medium mb-4">Introduction</h2>
        <p class="text-base leading-relaxed">
            This is a sample page showing custom base styles. 
            The text color is set to a dark gray, the background
            is white, and the font is sans-serif for a modern look.
        </p>
    </main>
</body>
  
</html>

這種方法使您的基礎樣式直接位於標記中,使它們更易於檢視和訪問。

如果您需要將您自己的自定義樣式應用於特定的HTML元素,您可以使用Tailwind的@layer指令將它們包含在Tailwind的基礎層中。

示例

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

@layer base {
    h1 {
      @apply text-3xl font-bold;
    }
    h2 {
      @apply text-xl font-semibold;
    }
    p {
      @apply text-base leading-relaxed;
    }
}

這些方法使您的基礎樣式保持一致,並使它們易於調整或擴充套件。使用theme函式或@apply指令將您主題中的值包含在您的自定義基礎樣式中。

新增元件類

使用components層為您的專案新增更復雜的類,同時仍然允許使用實用程式類進行覆蓋。

傳統上,您可能會在此類別中包含諸如modalalertdropdown之類的類。

示例

  /* main.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

@layer components {
    .modal {
      background-color: theme('colors.gray.800');
      border-radius: theme('borderRadius.md');
      padding: theme('spacing.4');
      box-shadow: theme('boxShadow.lg');
    }
    /* ... */
}

透過在components層中定義元件類,您仍然可以使用實用程式類根據需要調整它們。

示例

<!-- Modal with no shadow -->
<div class="modal shadow-none">
    <!-- ... -->
</div>

在Tailwind中,您可能會發現您比預期更少地使用這些元件類。有關如何有效重用樣式的提示,請檢視我們關於重用樣式的指南。

元件層非常適合為使用的第三方元件新增自定義樣式。

示例

/* main.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

@layer components {
    .custom-button {
      @apply bg-blue-500 text-white rounded-lg py-2 px-4;
    }
    .custom-input {
      @apply border border-gray-300 rounded-lg p-2;
    }
    .custom-card {
      @apply shadow-lg p-4 rounded-md;
    }
    /* ... */
}

使用theme函式或@apply指令將您主題中的值合併到這些自定義樣式中。

新增自定義實用程式

要新增您自己的自定義實用程式類,請使用utilities層

示例

    /* main.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

@layer utilities {
    .text-clip {
      text-overflow: clip;
    }
}

這有助於新增Tailwind預設情況下未涵蓋的CSS功能。

使用修飾符和自定義CSS

使用@layer新增的自定義樣式將自動支援Tailwind的修飾符語法,用於懸停狀態響應式設計等內容。

示例

    /* main.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

@layer utilities {
    .content-auto {
      content-visibility: auto;
    }
}

示例

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

您可以在懸停焦點其他狀態文件中找到有關這些修飾符如何工作的更多詳細資訊。

刪除未使用的自定義CSS

新增到basecomponentsutilities層的自定義樣式,只有在HTML中使用時才會出現在最終CSS中。

示例

/* main.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

@layer components {
    /* This will only be included if used in your HTML */
    .alert-box {
      /* ... */
    }
}

要確保始終包含某些自定義CSS,請直接將其新增到樣式表中,而無需使用@layer指令。

示例

/* main.css */
@tailwind base;
@tailwind components;

/* This will always be included in your final CSS */
.alert-box {
  /* ... */
}

@tailwind utilities;

記住要明智地定位自己以獲得正確的結果。例如,我們將.alert-box類放在@tailwind utilities之前,以便在必要時實用程式類仍然可以覆蓋它。

使用多個CSS檔案

使用多個CSS檔案時,請確保在使用Tailwind處理之前將其合併到單個樣式表中。否則,您可能會收到有關@layer@tailwind指令的錯誤。

您可以使用postcss-import外掛輕鬆合併檔案。

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

有關更多資訊,請參閱我們關於構建時匯入的文件

層和每個元件的CSS

在像VueSvelte這樣的元件框架中,您可以直接在每個元件檔案中的<style>塊中新增樣式。

您可以使用<style>元件樣式中的@apply和theme等功能,但@layer指令將無法正常工作。相反,您會遇到一個錯誤,指示在沒有相應的@tailwind指令的情況下使用了@layer

因此,請儘量不要在元件樣式中使用@layer

示例

<!-- Modal.vue -->
<template>
    <div class="modal">
      <slot></slot>
    </div>
</template>

<style>
    /* This will trigger an error because @layer isn't supported here */
    @layer components {
        .modal {
          background-color: theme('colors.gray.800');
          border-radius: theme('borderRadius.md');
          padding: theme('spacing.4');
        }
    }
</style>

發生這種情況是因為像VueSvelte這樣的框架會分別處理每個<style>塊。它們會獨立地對每個塊執行PostCSS外掛,因此Tailwind無法組合來自不同元件的樣式或正確處理@layer。每個<style>塊都是獨立處理的,彼此之間沒有了解。

一種解決方案是避免在元件樣式中使用@layer

直接應用樣式,無需使用@layer

示例

<!-- Modal.vue -->
<template>
    <div class="modal">
        <slot></slot>
    </div>
</template>

<style>
    /* This will trigger an error because @layer isn't supported here */
    .modal {
        background-color: theme('colors.gray.800');
        border-radius: theme('borderRadius.md');
        padding: theme('spacing.4');
    }
</style>

透過避免在元件樣式中使用@layer,您將失去對樣式優先順序的控制,這是由於這些工具的功能限制造成的。

我們建議您按其設計方式使用Tailwind:直接在HTML中應用Tailwind的實用程式類。這種方法確保您避免樣式處理問題,並充分利用Tailwind的功能。

使用Tailwind的實用程式類,而不是編寫自定義元件樣式

示例

<!-- Modal.vue -->
<template>
    <div class="bg-gray-800 rounded-md p-4">
        <slot></slot>
    </div>
</template>

這樣,您可以避免樣式處理問題,並充分利用Tailwind的實用程式類。

編寫外掛

無需為自定義樣式使用單獨的CSS檔案,您可以透過編寫自己的外掛來擴充套件Tailwind

tailwind.config.js

示例

const plugin = require('tailwindcss/plugin')

module.exports = {
    // ...
    plugins: [
      plugin(function ({ addBase, addComponents, addUtilities, theme }) {
        addBase({
          'p': {
            lineHeight: theme('lineHeight.relaxed'),
          },
          'a': {
            color: theme('colors.blue.600'),
            textDecoration: 'none',
          },
        })
        addComponents({
          '.alert': {
            backgroundColor: theme('colors.red.100'),
            border: `1px solid ${theme('colors.red.300')}`,
            borderRadius: theme('borderRadius.sm'),
            padding: theme('spacing.4'),
          }
        })
        addUtilities({
          '.text-clip': {
            textOverflow: 'clip',
          }
        })
      })
    ]
}

此方法允許您直接在Tailwind配置檔案中新增自定義樣式和實用程式,使您的工作流程更輕鬆,並保持樣式井然有序。有關建立您自己的外掛的更多詳細資訊,請檢視外掛文件

廣告