tailwind v4

简介

tailwind是一款高效开发的 css 原子化框架,它快速、灵活、可靠——无需运行时间。

安装

基于 vite 创建的项目

  1. 安装
1
$ pnpm install tailwindcss @tailwindcss/vite
  1. 配置插件
1
2
3
4
5
6
7
8
$ # vite.config.ts
$ import { defineConfig } from 'vite'
$ import tailwindcss from '@tailwindcss/vite'
$ export default defineConfig({
$ plugins: [
$ tailwindcss(),
$ ],
$ })
  1. 配置 css
1
$ @import "tailwindcss";

更多使用方法 👉tailwind

使用

函数和指令

@theme

定义自定义主题变量,整个项目可用,tailwind 会自动识别此类,可以像其他类一样使用。

1
2
3
4
5
6
$ @theme {
# 自定义颜色
$ --color-your-color: oklch(0.72 0.11 178);
$ # 自定义family
$ --font-family-your-font: 'your-font', sans-serif;
$ }
1
2
3
4
5
6
$
<div class="bg-your-color text-your-font">
$
<!-- ... -->
$
</div>

命名空间实用类

命名空间 描述 示例
--color-* 颜色实用程序 bg-red-500text-sky-300
--font-* 字体系列实用程序 font-sans
--text-* 字体大小实用程序 text-xl
--font-weight-* 字体粗细实用程序 font-bold
--tracking-* 字母间距实用程序 tracking-wide
--leading-* 行高实用程序 leading-tight
--breakpoint-_ 响应式断点变体 sm:
--container-* 容器查询变体和大小实用程序 @sm:*max-w-md
--spacing-* 间距和大小实用程序 px-4max-h-16
--radius-* 边框半径实用程序 rounded-sm
--shadow-* 盒子阴影实用程序 shadow-md
--inset-shadow-* 插入框阴影实用程序 inset-shadow-xs
--drop-shadow-* 阴影滤镜实用程序 drop-shadow-md
--blur-* 模糊滤镜实用程序 blur-md
--perspective-* 透视实用程序 perspective-near
--aspect-* 宽高比实用程序 aspect-video
--ease-* 过渡时间函数实用程序 ease-out
--animate-* 动画实用程序 animate-spin

@utility

使用 @utility 指令向您的项目添加可与 hover 、 focus 和 lg 等变体一起使用的自定义实用程序:

1
2
3
4
5
6
7
8
9
10
11
12
- @layer components {
- .btn {
- border-radius: 0.5rem;
- padding: 0.5rem 1rem;
- background-color: ButtonFace;
- }
- }
+ @utility btn {
+ border-radius: 0.5rem;
+ padding: 0.5rem 1rem;
+ background-color: ButtonFace;
+ }
1
2
3
$ @utility tab-* {
$ tab-size: --value("inherit", "initial", "unset");
$ }

@source

使用 @source 指令明确指定 Tailwind 自动内容检测未选取的源文件:

1
$ @import "tailwindcss" source("../src")

在扫描类名时,使用 @source not 忽略相对于样式表的特定路径:

1
$ @source not "../src/components/legacy";

禁用自动检测

1
2
3
$ @import "tailwindcss" source(none);
$ @source "../admin";
$ @source "../shared";

@apply

使用 @apply 指令将任何现有的实用程序类内联到您自己的自定义 CSS 中:

1
2
3
4
5
6
7
8
9
$ .select2-dropdown {
$ @apply rounded-b-lg shadow-md;
$ }
$ .select2-search {
$ @apply rounded border border-gray-300;
$ }
$ .select2-results__group {
$ @apply text-lg font-bold text-gray-900;
$ }

@reference

如果您想在 Vue 或 Svelte 组件的 <style> 块中或 CSS 模块中使用 @apply@variant ,则需要导入主题变量、自定义实用程序和自定义变体,以使这些值在该上下文中可用。

1
2
3
4
5
6
7
8
9
10
<template>
<h1>Hello world!</h1>
</template>

<style>
@reference "tailwindcss";
h1 {
@apply text-2xl font-bold text-red-500;
}
</style>

@config

使用 @config 指令加载基于旧式 JavaScript 的配置文件

1
$ @config "../../tailwind.config.js";

@plugin

使用 @plugin 指令加载基于旧版 JavaScript 的插件:

1
$ @plugin "@tailwindcss/typography";

结尾

本文只做简单介绍,更多内容及指令查找请查看 👉官方文档