Tailwind CSS - 重用樣式


Tailwind CSS 使用實用優先方法,您可以在其中應用小型、聚焦、單一用途的類來構建您的設計。此方法有助於避免複雜性並保持程式碼的一致性。

在處理專案時,您可能會發現自己在多個地方使用相同的實用程式類集。與其為重複的樣式編寫自定義 CSS,不如使用Tailwind 的實用程式類來有效地處理這些重複。

以下是在網頁上顯示配置檔案小部件的簡單示例,每個小部件都使用了三次相同的實用程式類。

示例

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

<body class="p-4 bg-gray-100">
    <div class="flex space-x-4 overflow-x-auto p-4 bg-gray-200">
        <!-- Profile Widget 1 -->
        <div class="flex-shrink-0 w-56 p-4 bg-white border border-gray-300
                    rounded-lg shadow-lg flex flex-col items-center space-y-3">
            <div class="mb-3">
                <img class="h-20 w-20 rounded-full border-4 border-cyan-500 
                            shadow-md" src="https://randomuser.me/api/portraits/men/1.jpg" 
                            alt="Profile Picture"/>
            </div>
            <div class="text-center">
                <h3 class="text-lg font-semibold text-gray-800 mb-1">John Doe</h3>
                <p class="text-gray-600 text-sm mb-2">Tech Enthusiast</p>
                <p class="text-gray-500 text-xs">John has over 5 years of 
                    experience in the tech industry, focusing on software 
                    development and innovation.
                </p>
            </div>
        </div>

        <!-- Profile Widget 2 -->
        <div class="flex-shrink-0 w-56 p-4 bg-white border border-gray-300 
                    rounded-lg shadow-lg flex flex-col items-center space-y-3">
            <div class="mb-3">
                <img class="h-20 w-20 rounded-full border-4 border-rose-500 
                            shadow-md" src="https://randomuser.me/api/portraits/women/2.jpg" 
                            alt="Profile Picture"/>
            </div>
            <div class="text-center">
                <h3 class="text-lg font-semibold text-gray-800 mb-1">
                  Jane Smith
                </h3>
                <p class="text-gray-600 text-sm mb-2">UI/UX Designer</p>
                <p class="text-gray-500 text-xs">Jane is a skilled UI/UX 
                    designer with 3 years of experience in creating intuitive user
                    interfaces and enhancing user experiences.
                </p>
            </div>
        </div>

        <!-- Profile Widget 3 -->
        <div class="flex-shrink-0 w-56 p-4 bg-white border border-gray-300 
                    rounded-lg shadow-lg flex flex-col items-center space-y-3">
            <div class="mb-3">
                <img class="h-20 w-20 rounded-full border-4 border-violet-500 
                            shadow-md" src="https://randomuser.me/api/portraits/men/3.jpg" 
                            alt="Profile Picture"/
                >
            </div>
            <div class="text-center">
                <h3 class="text-lg font-semibold text-gray-800 mb-1">
                    Alice Johnson</h3>
                <p class="text-gray-600 text-sm mb-2">Data Scientist</p>
                <p class="text-gray-500 text-xs">Alice has 7 years 
                    of experience as a data scientist, specializing in data 
                    analysis and machine learning.
                </p>
            </div>
        </div>
    </div>
</body>

</html>

不用擔心!我們將幫助您瞭解如何在專案中重用樣式以及何時有效地使用每種方法。

使用編輯器和語言功能

通常,重複樣式不是問題,因為它們都在一個地方或使用迴圈建立,因此您只需編寫一次程式碼。

如果您在一個檔案中工作,請使用多游標編輯一次更改多行。對於重複的元素,請使用迴圈從一段程式碼生成它們。這使您的工作保持高效和有序。

多游標編輯

多游標編輯是許多文字編輯器中的一項功能,它使您能夠在文件中的不同位置放置多個游標。這使您能夠立即在多個位置進行相同的更改,使其非常適合快速更新重複的內容。

當您在一個檔案中具有重複的樣式或元素時,多游標編輯可以幫助您一次修改所有這些元素。讓我們看一個示例來了解它是如何工作的。

假設您有以下專案列表,並且您希望將每個專案的類bg-red-100更新為bg-teal-100

示例

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

<body class="p-4">
    <h3 class="font-bold underline mb-4">
        List of Item in Shopping cart:
    </h3>
    <ul class="shopping-cart">
        <li class="bg-red-100 p-2">Apples</li>
        <li class="bg-red-100 p-2">Bananas</li>
        <li class="bg-red-100 p-2">Oranges</li>
        <li class="bg-red-100 p-2">Grapes</li>
    </ul>
</body>

</html>

新增游標

按住 Alt 鍵並點選程式碼中每個 bg-red-100 旁邊。這將在您點選的每個位置放置一個游標,並且所有游標都到位後,鍵入 bg-teal-100。所有 bg-red-100 的例項將立即更新為 bg-teal-100。

更新後的程式碼

<ul class="shopping-cart">
    <li class="bg-teal-100 p-2">Apples</li>
    <li class="bg-teal-100 p-2">Bananas</li>
    <li class="bg-teal-100 p-2">Oranges</li>
    <li class="bg-teal-100 p-2">Grapes</li>
</ul> 

您可能會發現,使用多游標編輯通常是處理重複樣式的最簡單方法。它可以幫助您一次更新所有例項,因此您不需要額外的工具或方法。

迴圈

程式設計中的迴圈使處理重複元素變得更容易。您可以使用迴圈自動建立相同的 HTML 結構,而不是一遍又一遍地編寫相同的程式碼。因此,在 Web 專案中使用重複的設計元素時,務必有效地使用迴圈。

在為每個重複的設計元素建立單獨的元件或自定義類之前,請檢查您是否多次使用該元素。

例如,本指南開頭顯示的個人資料部件使用了相同的設計重複三次。與其單獨編寫每個部件,我們可以使用迴圈從單個模板生成多個元素。讓我們看看下面的示例是如何工作的。

示例

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

<body class="p-4">
    <div id="profile-container" class="flex space-x-4 overflow-x-auto 
        p-4 bg-gray-200">
    <!-- Profile Widgets will be dynamically inserted here -->
    </div>
    <script>
        document.addEventListener('DOMContentLoaded', () => {
          const profiles = [
            { name: "John Doe", role: 
                "Tech Enthusiast", 
                imgSrc: "https://randomuser.me/api/portraits/men/1.jpg", 
                    
                        borderColor: "border-cyan-500" },
            { name: "Jane Smith", role: "UI/UX Designer", 
                imgSrc: "https://randomuser.me/api/portraits/women/2.jpg", 
                    borderColor: "border-rose-500" },
            { name: "Alice Johnson", role: "Data Scientist", 
                imgSrc: "https://randomuser.me/api/portraits/men/3.jpg", 
                    borderColor: "border-violet-500" }
          ];
    
          const container = document.getElementById('profile-container');
          profiles.forEach(profile => {
            container.innerHTML += `
              <div class="flex-shrink-0 w-56 p-4 bg-white border 
                border-gray-300 rounded-lg shadow-lg flex flex-col items-center space-y-3">
                <div class="mb-3">
                  <img class="h-20 w-20 rounded-full border-4 ${profile.borderColor} shadow-md" 
                    src="${profile.imgSrc}" alt="Profile Picture"/>
                </div>
                <div class="text-center">
                  <h3 class="text-lg font-semibold text-gray-800 mb-1">
                    ${profile.name}</h3>
                  <p class="text-gray-600 text-sm mb-2">
                    ${profile.role}</p>
                  <p class="text-gray-500 text-xs">Profile description here.</p>
                </div>
              </div>
            `;
          });
        });
    </script> 
</body>

</html>

使用迴圈意味著您只需編寫一次標記,避免重複並使更新更容易。它可以有效地管理動態資料,並確保更改在一個地方應用。

提取元件和部分

如果您希望在不同的檔案中重用樣式,如果您使用的是像ReactSvelteVue這樣的前端框架,最好建立一個元件。如果您使用的是像BladeERBTwigNunjucks這樣的模板語言,則應建立一個模板部分。這種方法有助於保持程式碼井井有條,並使其更容易維護。

示例

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

<body class="p-4">
  <div class="testimonial-sectio">
        <div class="testimonial-card p-4 bg-white border border-gray-300 
                    rounded-lg shadow-lg">
            <img class="w-16 h-16 rounded-full border-2 border-gray-300" 
              src="https://randomuser.me/api/portraits/men/1.jpg" 
                  alt="Alice Johnson's photo" />
            <h3 class="mt-2 text-lg font-semibold text-gray-800">
                Alice Johnson
            </h3>
            <p class="mt-1 text-gray-600">
                This service is fantastic! It exceeded all my expectations.
            </p>
        </div>
        
        <div class="testimonial-card p-4 bg-white border border-gray-300 
                    rounded-lg shadow-lg mt-4">
            <img class="w-16 h-16 rounded-full border-2 border-gray-300" 
              src="https://randomuser.me/api/portraits/women/2.jpg" 
                  alt="Bob Smith's photo" />
            <h3 class="mt-2 text-lg font-semibold text-gray-800">
                Bob Smith
            </h3>
            <p class="mt-1 text-gray-600">
                An excellent experience from start to finish.
            </p>
        </div>
    </div>
</body>

</html>

對於上面的示例,使用Tailwind CSS在React中建立一個TestimonialCard元件,並在您的專案中根據需要使用它多次。下面是一個您可以用來顯示推薦的函式式元件

示例

// TestimonialCard.jsx
import React from 'react';

const TestimonialCard = ({ name, photo, testimonial }) => (
    <div className="p-4 bg-white border border-gray-300 rounded-lg shadow-lg">
        <img 
            className="w-16 h-16 rounded-full border-2 border-gray-300" 
            src={photo} 
            alt={`${name}'s photo`} 
        />
        <h3 className="mt-2 text-lg font-semibold text-gray-800">{name}</h3>
        <p className="mt-1 text-gray-600">{testimonial}</p>
    </div>
);

export default TestimonialCard;

要在您的應用程式或設計中使用TestimonialCard元件,只需匯入它並提供必要的props即可。

示例

// App.jsx
import React from 'react';
import TestimonialCard from './TestimonialCard';

const App = () => (
    <div className="p-4 bg-gray-100">
        <div className="flex space-x-4">
            <TestimonialCard
                name="John Doe"
                photo="https://randomuser.me/api/portraits/men/1.jpg"
                  testimonial="John's experience was wonderful. 
                  The service was top-notch and exceeded expectations."
            />
            <TestimonialCard
                name="Jane Smith"
                photo="https://randomuser.me/api/portraits/women/2.jpg"
                  testimonial="Jane had a fantastic experience! 
                  Highly recommended for anyone looking for quality service."
            />
        </div>
    </div>
);

export default App;

在任何地方使用此元件,並輕鬆地從一個地方更新樣式。

與CSS抽象相比

在設計網頁介面時,僅靠CSS不足以處理複雜的元件。您需要HTML和CSS來有效地處理詳細的UI元素。

以“進度跟蹤器”為例。與其使用CSS單獨為每個步驟設定樣式,不如使用一個元件為每個步驟組合HTML和CSS。

示例

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

<body class="flex justify-center items-center h-screen bg-gray-100">
    <div class="w-full max-w-3xl px-4 py-6 bg-white rounded-lg shadow-md">
        <div class="text-center mb-8 text-gray-800">
            <p class="text mb-4 ml-4">
                This tracker shows your progress through different stages:
            </p>
            <ul class="list-disc list-inside text-left text-gray-600">
                <li><strong class="text-green-500">Completed:</strong> 
                    Finished steps
                </li>
                <li><strong class="text-yellow-500">Current:</strong>
                    The active step
                </li>
                <li><strong class="text-gray-300">Upcoming:</strong>
                    Future steps
                </li>
            </ul>
        </div>
        <div class="relative flex items-center">
            <div class="absolute inset-0 flex items-center pointer-events-none">
                <div class="flex-1 h-1 bg-green-500"></div>
                <div class="flex-1 h-1 bg-yellow-400"></div>
                <div class="flex-1 h-1 bg-gray-300"></div>
                <div class="flex-1 h-1 bg-gray-300"></div>
            </div>
            <!-- Steps -->
            <div class="flex-1 text-center relative z-10">
                <div class="w-12 h-12 rounded-full bg-green-500 text-white 
                    flex items-center justify-center mx-auto mb-2 text-2xl">✔</div>
                <div class="text-sm">Step 1</div>
            </div>
            <div class="flex-1 text-center relative z-10">
                <div class="w-12 h-12 rounded-full bg-yellow-500 text-white 
                    flex items-center justify-center mx-auto mb-2 text-2xl">▶</div>
                <div class="text-sm">Step 2</div>
            </div>
            <div class="flex-1 text-center relative z-10">
                <div class="w-12 h-12 rounded-full bg-gray-200 text-white 
                    flex items-center justify-center mx-auto mb-2 text-2xl">•</div>
                <div class="text-sm">Step 3</div>
            </div>
            <div class="flex-1 text-center relative z-10">
                <div class="w-12 h-12 rounded-full bg-gray-200 text-white
                    flex items-center justify-center mx-auto mb-3 text-2xl">•</div>
                <div class="text-sm">Step 4</div>
            </div>
            <div class="absolute right-0 top-1/2 w-1/4 h-px bg-gray-300"></div>
        </div>
    </div>
</body>

</html>
 

即使您使用類進行樣式設定,每次使用元件時最終也會重複HTML。雖然更新字型大小很簡單,但僅使用CSS進行更復雜的更改(例如將標題轉換為連結)則很困難。

元件和模板部分更好,因為它們結合了HTML樣式。這樣,您就可以在一個地方更新字型大小或將所有標題更改為連結。

考慮使用模板部分JavaScript元件來獲得更簡單的解決方案。

示例

import React from 'react';

function Step({ status, number }) {
    const statusClasses = {
        completed: 'bg-green-500',
        current: 'bg-yellow-500',
        upcoming: 'bg-gray-200'
    };

    return (
        <div className="flex-1 text-center relative z-10">
            <div className={`w-12 h-12 rounded-full ${statusClasses[status]} 
                text-white flex items-center justify-center mx-auto mb-2 text-2xl`}>
                {status === 'completed' ? '✔' : status === 'current' ? '▶' : '•'}
            </div>
            <div className="text-sm">Step {number}</div>
        </div>
    );
}

function ProgressTracker() {
    return (
        <div className="relative flex items-center">
            <div className="absolute inset-0 flex items-center pointer-events-none">
                <div className="flex-1 h-1 bg-green-500"></div>
                <div className="flex-1 h-1 bg-yellow-400"></div>
                <div className="flex-1 h-1 bg-gray-300"></div>
                <div className="flex-1 h-1 bg-gray-300"></div>
            </div>
            <Step status="completed" number={1} />
            <Step status="current" number={2} />
            <Step status="upcoming" number={3} />
            <Step status="upcoming" number={4} />
            <div className="absolute right-0 top-1/2 w-1/4 h-px bg-gray-300"></div>
        </div>
    );
}

export default ProgressTracker;

使用元件模板部分,您只需要實用程式類,因為樣式在一個地方處理。

使用Tailwind的@apply指令提取類

在設計網頁時,重複使用相同的實用程式類會導致您的HTML變得雜亂且難以管理。Tailwind CSS透過@apply指令來幫助解決這個問題。

什麼是@apply以及何時使用它?

@apply指令允許您透過應用一組Tailwind實用程式類來建立自定義CSS類。這透過將重複的樣式移動到您的CSS檔案中來保持HTML更簡潔。

雖然模板部分適用於複雜的元件,但@apply非常適合於頻繁使用的樣式。它有助於保持HTML整潔並保持樣式的一致性。

在使用@apply之前,您可能會在HTML中直接新增多個實用程式類來設定卡片的樣式。

示例

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

<body class="p-4 bg-gray-200">
    <div class="p-6 max-w-sm mx-auto bg-white rounded-lg shadow-md">
        <h2 class="text-xl font-bold mb-2">Card Title</h2>
        <p class="text-gray-700 ">
            This is a card component styled with Tailwind utilities.
        </p>
    </div>
</body>

</html>

使用@apply後:在您的CSS中定義一個用於卡片的自定義類,然後在您的HTML中使用它。

<div class="card">
    <h2 class="card-title">Card Title</h2>
    <p class="card-content">
        This is a card component 
        styled with Tailwind utilities.
    </p>
</div>

帶有@apply的CSS

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

@layer components {
  .card {
    @apply p-6 max-w-sm mx-auto bg-white rounded-lg shadow-md;
  }
  .card-title {
    @apply text-xl font-bold mb-2;
  }
  .card-content {
    @apply text-gray-700;
  }
}

使用@apply指令有助於您保持樣式井井有條並使程式碼更簡潔。

避免過早抽象

不要僅僅為了清理HTML而使用@apply。這似乎是一個好主意,但它可能會帶來更多問題。

  • 命名問題:想出類名可能會讓人感到疲憊。
  • 多次編輯:過度使用@apply意味著需要不斷在CSS和HTML之間切換。
  • 樣式更改:對一個類的更改可能會意外地影響您網站的其他部分。
  • 更大的CSS檔案:許多自定義類會增加CSS檔案的大小並影響效能。

對於像按鈕這樣的小型可重用專案,請使用@apply,或者在像React這樣的框架中使用元件以進行更好的管理。

廣告