Tailwind CSS 怎么添加自定义样式?

文章导读
Previous Quiz Next 在 Tailwind CSS 中,添加自定义样式 意味着向框架中添加你自己独特的样式。
📋 目录
  1. 自定义你的 Tailwind 主题
  2. Tailwind CSS 中的任意值
  3. 任意属性
  4. Tailwind CSS 中的任意变体
  5. 处理空白字符
  6. 解决歧义
  7. 使用 CSS 和 @layer
  8. Tailwind 为什么将样式分组到 layers 中?
  9. Tailwind CSS 中添加基础样式
  10. 添加组件类
A A

Tailwind CSS - 添加自定义样式


Previous
Quiz
Next

在 Tailwind CSS 中,添加自定义样式 意味着向框架中添加你自己独特的样式。

通常,任何框架的挑战在于,当它无法提供你所需的一切时,知道该怎么办。Tailwind 被设计为灵活且可自定义的,因此你可以调整它以适应你的项目。

我们将指导你调整设计设置、添加自定义 CSS,以及使用 plugins 来提升 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 中使用你的自定义 font sizesborder styles。以下是应用方法。

示例

<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>     

有关 自定义 你的主题的更多细节,请查看 Theme Configuration documentation

Tailwind CSS 中的任意值

Tailwind CSS 中,你通常使用预定义的设计设置来样式化你的元素。但是,当你需要对设计进行更精确控制时,Tailwind 允许你使用 arbitrary values

有时,你的设计需求可能不符合 Tailwind 的默认 选项。例如,你可能需要一个独特的边框宽度或内边距,这些在 标准配置 中不可用。Arbitrary values 允许你直接在类名中设置这些自定义尺寸,从而获得你想要的精确外观。

要在 Tailwind CSS 中应用 arbitrary values,请使用 方括号 记法。这允许你直接将任何有效的 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 像素的内边距,展示了 arbitrary values 的用法。

你可以将 arbitrary values 用于间距和定位等。这里是一个使用特定值定位元素并使其响应式的示例。

示例

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

在这里,top-[117px] 将位置设置为距离顶部 117 像素,而 lg:top-[344px] 在大屏幕上将其移动到距离顶部 344 像素。

Arbitrary values 也可以用于背景颜色、字体大小和伪元素。

示例

<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 中的 arbitrary properties 允许你使用方括号直接在 utility classes 中使用自定义 CSS 值。

有时,你可能需要一个未包含在 Tailwind utilities 中的 CSS 属性。例如,如果你需要一个默认不可用的特定 backdrop-filter 效果,可以使用 arbitrary values

示例

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

你还可以使用 Tailwind CSS 的 arbitrary values 结合修饰符实现动态样式。例如,在 hover 时调整元素的 backdrop-filter

示例

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

Tailwind CSS 的 arbitrary values 可用于根据条件(如屏幕尺寸)调整 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 中的任意变体

Arbitrary variants 在 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>

查看 arbitrary variants documentation 以获取更多细节。

处理空白字符

处理空白字符 在 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')]....">
    <!-- 在 URL 中使用下划线的示例 -->
</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 中,一些 utility classes 名称相似但应用于不同的 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 variables 上。例如,如果你使用 text-[var(--my-var)],Tailwind 无法判断 --my-var 是 font size 还是 color。

假设你有一个用于大小或颜色的 CSS variable,如下所示。

示例

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

在这个示例中,--my-value 可以用于各种目的,如 font size 或 color。

为了明确 var(--my-value) 的用途,你可以显式指定类型。这有助于 Tailwind 精确理解如何应用 CSS variable。

如果 --my-value 意为 font size,或者如果 --my-value 意为 color,那么你应该以这种方式使用它。

示例

<!-- 使用 CSS variable 的字体大小 -->
<div class="text-[length:var(--font-size)]">
    This text uses a CSS variable for font size.
</div>

<!-- 使用 CSS variable 的颜色 -->
<div class="text-[color:var(--text-color)]">
    This text uses a CSS variable for color.
</div>

使用 CSS 和 @layer

在使用 Tailwind CSS 时,你可能需要一些其 utility 不覆盖的自定义样式。使用 @layer 指令 将这些样式添加到 Tailwind 的系统中,以实现正确的排序和优化。

对于简单的自定义 CSS,你可以直接将其添加到你的样式表中。

示例

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

.custom-button {
    background-color: #4a90e2; /* 自定义背景色 */
    border-radius: 12px;      /* 自定义边框半径 */
    color: white;              /* 自定义文本颜色 */
    padding: 10px 20px;        /* 自定义内边距 */
    text-align: center;        /* 文本居中 */
}

为了获得更多控制,使用 @layer 指令 将自定义样式添加到 Tailwind 的 base、componentsutilities layers 中。这有助于你的样式与 Tailwind 的现有系统良好配合。

示例

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

@layer components {
    .custom-button {
        background-color: #4a90e2; /* 自定义背景色 */
        border-radius: 12px;      /* 自定义边框半径 */
        color: white;              /* 自定义文本颜色 */
        padding: 10px 20px;        /* 自定义内边距 */
        text-align: center;        /* 文本居中 */
        box-shadow: 0 4px 8px rgba(0,0,0,0.2); /* 自定义阴影 */
        font-size: 16px;           /* 自定义字体大小 */
    }
}

Tailwind 为什么将样式分组到 layers 中?

Tailwind 将样式分组 到 layers 中,以管理它们之间的交互方式以及优先级。这有助于防止冲突,并确保样式以一致且有序的方式应用。

示例

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

如果同时使用这两个样式。

示例

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

文本将显示为 24px,因为 .text-large.header 之后,因此具有更高的优先级。

Tailwind 将样式组织成三个 layers:

  • Base Layer: 应用默认样式,设置基本外观,如字体和颜色。
  • Components Layer: 为特定元素添加样式,例如按钮,便于重复使用。
  • Utilities Layer: 包含小型、单一用途的样式,可以覆盖其他 layers 中的任何内容,用于精确的设计调整。

明确样式之间的交互方式使它们更容易管理。@layer 指令 帮助你控制样式的最终顺序,同时允许你按自己的喜好组织代码。

Tailwind CSS 中的 @layer 指令 允许你将自定义样式添加到 Tailwind 的现有 layers 中。它保持你的样式组织有序,与 Tailwind 的 utilities 良好协作,并支持如 modifierstree-shaking 等功能,以提升性能。

Tailwind CSS 中添加基础样式

要在 Tailwind CSS 中为页面设置默认样式(如文本颜色或背景颜色),只需直接在 <html> 或 <body> 元素中添加 class。

示例

<!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>

这种方法将基础样式直接保存在 markup 中,使其更易于查看和访问。

如果需要为特定 HTML 元素应用自定义样式,可以使用 Tailwind 的 @layer 指令 将其包含在 Tailwind 的 base layer 中。

示例

@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 function 或 @apply 指令theme 中的值纳入自定义 base styles

添加组件类

使用 components layer 为项目添加更复杂的 class,同时仍允许使用 utility classes 进行覆盖。

传统上,你可能会将 modalalertdropdown 等 class 归入此类。

示例

  /* 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 layer 中定义组件类,你仍然可以使用 utility classes 根据需要调整它们。

示例

<!-- 无阴影的 Modal -->
<div class="modal shadow-none">
    <!-- ... -->
</div>

在 Tailwind 中,你可能会发现这些 component class 的使用频率低于预期。有关有效重用样式的提示,请查看我们的 Reusing Styles 指南。

component layer 非常适合为使用的第三方组件添加自定义样式。

示例

/* 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 function 或 @apply 指令将 theme 中的值融入这些自定义样式。

添加自定义 utilities

要添加自己的 custom utility class,请使用 utilities layer

示例

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

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

这对于添加 Tailwind 默认未覆盖的 CSS 功能非常有用。

使用修饰符与自定义 CSS

使用 @layer 添加的自定义样式将自动支持 Tailwind 的修饰符语法,例如 hover 状态响应式设计

示例

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

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

示例

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

您可以在 HoverFocus其他状态 文档中找到更多关于这些修饰符工作原理的详细信息。

移除未使用的自定义 CSS

您添加到 basecomponentsutilities 层中的自定义样式,只有在您的 HTML 中使用时才会出现在最终的 CSS 中。

示例

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

@layer components {
    /* 只有在您的 HTML 中使用时才会包含此样式 */
    .alert-box {
      /* ... */
    }
}

要确保某些自定义 CSS 始终被包含,请直接将其添加到样式表中,而不使用 @layer 指令。

示例

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

/* 此样式将始终包含在最终的 CSS 中 */
.alert-box {
  /* ... */
}

@tailwind utilities;

请明智地定位您的样式以获得正确的结果。例如,我们将 .alert-box 类放置在 @tailwind utilities 之前,以便在必要时 utility classes 仍能覆盖它。

使用多个 CSS 文件

在使用多个 CSS 文件时,请确保在使用 Tailwind 处理之前将它们合并为单个样式表。否则,您可能会遇到关于 @layer@tailwind 指令的错误。

您可以使用 postcss-import 插件轻松合并文件。

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

更多信息,请参阅我们的 构建时导入 文档。

层和组件级 CSS

在像 VueSvelte 这样的组件框架中,你可以在每个组件文件中直接在 <style> 块中添加样式。

你可以在 component styles 中使用像 @apply 和 theme 这样的功能,但 @layer 指令将无法正常工作。相反,你会遇到一个错误,提示 @layer 在没有对应的 @tailwind 指令的情况下被使用。

因此,尽量不要在 component styles 中使用 @layer

示例

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

<style>
    /* 这将触发错误,因为这里不支持 @layer */
    @layer components {
        .modal {
          background-color: theme('colors.gray.800');
          border-radius: theme('borderRadius.md');
          padding: theme('spacing.4');
        }
    }
</style>

这是因为像 VueSvelte 这样的框架会分别处理每个 <style> 块。它们独立地在每个块上运行 PostCSS plugins,因此 Tailwind 无法合并不同组件的样式或正确处理 @layer。每个 <style> 块都是孤立处理的,不知道其他块的存在。

一种解决方案是在 component styles 中避免使用 @layer

直接应用样式,而不使用 @layer

示例

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

<style>
    /* 这将触发错误,因为这里不支持 @layer */
    .modal {
        background-color: theme('colors.gray.800');
        border-radius: theme('borderRadius.md');
        padding: theme('spacing.4');
    }
</style>

通过在 component styles 中避免使用 @layer,你将失去对样式优先级的控制,这是这些工具工作方式所导致的限制。

我们推荐按照 Tailwind 的设计方式使用它:直接在你的 HTML 中应用 Tailwind's utility classes。这种方法确保你避免样式处理问题,并充分利用 Tailwind 的功能。

使用 Tailwind's utility classes,而不是编写自定义的 component styles

示例

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

这样,你可以避免样式处理问题,并充分利用 Tailwind's utility classes。

编写插件

与其为自定义样式使用单独的 CSS 文件,你可以通过编写自己的 plugins 来扩展 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 configuration file 中添加自定义样式和 utilities,使你的工作流程更简单,并保持样式组织有序。有关创建自己的 plugins 的更多细节,请查看 Plugins documentation