發布於 2023-03-16

更新於 2023-03-17

程式

約663字 (4分鐘閱讀)

[Day 24] Tailwind 自定義樣式 - 嘗試 30 日寫文充版挑戰

Title Image

Photo by TailwindCSS on TailwindCSS

前言 - Prologue

嘗試寫 30 天文充實版面 (跳過假日 ლ(́◕◞౪◟◕‵ლ) ) 更新文章的 Day 24

Tailwind 是一個快速開發網頁的框架,提供了許多現成的樣式可以使用。但當想要為網站創造獨特的風格時,自定義樣式是不可或缺的。

在本文中,將介紹如何在 React 中使用 Tailwind 自定義樣式。透過這個功能,可以在 Tailwind 的基礎上加入自己的風格,創造出專屬於個人的設計風格。

接下來將會介紹如何加入自定義樣式,讓您可以輕鬆地在 React 應用程序中使用 Tailwind 自定義樣式。

正文 - Main text

在 Tailwind 中新增自定義樣式,有以下幾種方式:

tailwind.config.js 中自定義樣式

tailwind.config.js 檔案中的 theme 屬性下,可以新增自己的自定義樣式。

例如,如果想要新增一個叫做 .custom-color 的樣式,可以在 theme 中新增如下的屬性:

module.exports = {
  theme: {
    extend: {
      colors: {
        'custom': '#F8FAFC',
      },
    },
  },
  variants: {},
  plugins: [],
};

這樣一來,就可以在 HTML 中使用 bg-customtext-custom 等類別來套用該自定義顏色了。

使用 @apply 關鍵字套用自定義樣式

在 CSS 中,可以使用 @apply 關鍵字來套用自定義樣式,如下所示:

.custom-btn {
  @apply bg-red-500 text-white py-2 px-4 rounded-lg;
}

這樣一來,就可以在 HTML 中使用 custom-btn 類別來套用自定義樣式了。

在 HTML 中使用 style 屬性設定自定義樣式

如果只想對某一個元素套用自定義樣式,可以直接在 HTML 中使用 style 屬性來設定自定義樣式,例如:

<div style="
  background-color: #F8FAFC;
  color: #333333;
  padding: 1rem;"
>
  This is a custom styled div.
</div>

這樣一來,就可以設定該元素的自定義樣式了。

Q&A Example

Q: 如果我想新增一個叫做 mt-100vhmargin-top: 100vh; 和叫 text-smplusfont-size: 0.938rem;,還有叫 font-Arialfont-family: Arial, Helvetica, sans-serif; 該怎麼做?

A:tailwind.config.js 中的 theme.extend 中新增屬性。

module.exports = {
  theme: {
    extend: {
      margin: {
        '100vh': '100vh',
      },
      fontSize: {
        'smplus': '0.938rem',
      },
      fontFamily: {
        'arial': ['Arial', 'Helvetica', 'sans-serif'],
      },
    },
  },
  variants: {},
  plugins: [],
};

後記 - Epilogue

在使用過程中,我發現 UNOCSS 相對於 Tailwind 還是更加靈活與直覺性,能夠更好地滿足一些特定的需求,如更高度的自定義性和更細膩的設計控制。ლ(゚д゚ლ)

而無論選擇哪種 CSS 框架,我認為了解如何在其中新增自定義樣式都是非常重要的。這可以幫助在需要時快速定制樣式,創造獨特的使用者體驗。

[Day 24] Tailwind 自定義樣式 - 嘗試 30 日寫文充版挑戰

https:///blog/43

作者

Kama

Read more from 程式
lightbox-image
Toggle Button - Red Pandas Icons by svgrepo.com

Copyrights © 2023 Kama, All Rights Reserved.