tailwindcss - 添加自定义样式

644 阅读3分钟

覆盖原有样式

// tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
  theme: {
    screens: {
      sm: '480px',
      md: '768px',
      lg: '976px',
      xl: '1440px',
    },
    colors: {
      'blue': '#1fb6ff',
      'pink': '#ff49db',
      'orange': '#ff7849',
      'green': '#13ce66',
      'gray-dark': '#273444',
      'gray': '#8492a6',
      'gray-light': '#d3dce6',
    },
    fontFamily: {
      sans: ['Graphik', 'sans-serif'],
      serif: ['Merriweather', 'serif'],
    },
    extend: {
      spacing: {
        '128': '32rem',
        '144': '36rem',
      },
      borderRadius: {
        '4xl': '2rem',
      }
    }
  }
}

使用变量

可以使用 theme 函数来引用 tailwind.config.js 文件中样式

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

不需要将变量包装在 var(...) 中

<div class="bg-[--my-color]">
  <!-- ... -->
</div>

任意 css

<div class="[--scroll-offset:56px] lg:[--scroll-offset:44px]">
  <!-- ... -->
</div>

变体

<ul role="list">
  {#each items as item}
    <li class="lg:[&:nth-child(3)]:hover:underline">{item}</li>
  {/each}
</ul>

处理空白

变量使用下划线( _ )代替空格

<div class="grid grid-cols-[1fr_500px_2fr]">
  <!-- ... -->
</div>

url 函数下划线不会将其转换为空格

<div class="bg-[url('/what_a_rush.png')]">
  <!-- ... -->
</div>

反斜杠转义下划线,不会将其转换为空格

<div class="before:content-['hello\_world']">
  <!-- ... -->
</div>

JSX 里面使用 String.raw 不会将其转换为空格

<div className={String.raw`before:content-['hello\_world']`}>
  <!-- ... -->
</div>

命名空间冲突

Tailwind 中的许多实用程序共享一个公共名称空间,但映射到不同的 CSS 属性。例如, text-lg 和 text-black 都共享 text- 命名空间,但一个用于 font-size ,另一个用于 color 。

<div class="text-[var(--my-var)]">...</div>

可以通过在值之前添加 CSS 数据类型来提示 Tailwind 的基础类型

<!-- Will generate a font-size utility -->
<div class="text-[length:var(--my-var)]">...</div>

<!-- Will generate a color utility -->
<div class="text-[color:var(--my-var)]">...</div>

使用 CSS 和 @layer

添加真正自定义的 CSS 时,将自定义 CSS 添加到样式表中

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

.my-custom-style {
  /* ... */
}

为了获得更强大的功能,您还可以使用 @layer 指令向 Tailwind的 base , components 和 utilities 层添加样式

可以使用修饰器和去除没有用到的 css

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

@layer components {
  .my-custom-style {
    /* ... */
  }
}

添加基础样式

html 或 body 元素中添加 class

<!doctype html>
<html lang="en" class="text-gray-900 bg-gray-100 font-serif">
  <!-- ... -->
</html>

如果你想为特定的HTML元素添加你自己的默认基本样式,使用 @layer 指令将这些样式添加到 Tailwind 的 base 层:

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

@layer base {
  h1 {
    @apply text-2xl;
  }
  h2 {
    @apply text-xl;
  }
  /* ... */
}

自定义基础样式时使用 theme 函数或 @apply 指令引用 theme 文件的属性。

添加组件级别 class

使用 components 层来添加任何更复杂的 class 到项目中,您仍然希望能够使用实用程序类进行覆盖。

@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');
  }
  /* ... */
}
<!-- Will look like a card, but with square corners -->
<div class="card rounded-none">
  <!-- ... -->
</div>

components 层也是一个很好的地方,可以为您正在使用的任何第三方组件放置自定义样式

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

@layer components {
  .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;
  }
  /* ... */
}

添加自定义工具 class

当你想在你的项目中使用一个CSS功能,而Tailwind 不包括开箱即用的实用程序时,添加自定义工具 class 到 Tailwind的 utilities 层

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

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

自定义 class 和修饰符结合使用

使用 @layer 添加到 Tailwind 的任何自定义样式都将自动支持 Tailwind 的修饰符语法

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

@layer utilities {
  .content-auto {
    content-visibility: auto;
  }
}
<div class="lg:dark:content-auto">
  <!-- ... -->
</div>

删除未使用的自定义CSS

您添加到 base , components 或 utilities 层的任何自定义样式如果没有用到会被删除。如果始终保留不要使用 @layer

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

@layer components {
  /* This won't be included in your compiled CSS unless you actually use it */
  .card {
    /* ... */
  }
}
@tailwind base;
@tailwind components;

/* This will always be included in your compiled CSS */
.card {
  /* ... */
}

@tailwind utilities;

使用多个CSS文件

如果你写了很多 CSS 并将其组织成多个文件,请确保在使用 Tailwind 处理它们之前将这些文件合并到一个样式表中,否则你会看到关于使用 @layer 而没有相应的 @tailwind 指令的错误。

最简单的方法是使用postcss-import插件

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

layer 和单文件样式

可以使用 @apply 和 theme 这样的特性,但 @layer 指令将不起作用

插件

// tailwind.config.js
const plugin = require("tailwindcss/plugin");
module.exports = {
  // ...
  plugins: [
    plugin(function ({ addBase, addComponents, addUtilities, theme }) {
      addBase({
        h1: {
          fontSize: theme("fontSize.2xl"),
        },
        h2: {
          fontSize: theme("fontSize.xl"),
        },
      });
      addComponents({
        ".card": {
          backgroundColor: theme("colors.white"),
          borderRadius: theme("borderRadius.lg"),
          padding: theme("spacing.6"),
          boxShadow: theme("boxShadow.xl"),
        },
      });
      addUtilities({
        ".content-auto": {
          contentVisibility: "auto",
        },
      });
    }),
  ],
};