# Tailwind

返回:前端开源 | https://github.com/tailwindcss/tailwindcss

Tailwind CSS

Tailwind CSS 是一个利用公用程序类(Utilize Class,下文皆称 Utilize Class)的 CSS 框架。

许多人会想到 CSS 框架,有很多,例如 Bootstrap、Bulma 和 Material UI。Bootstrap 和 Bulma 等框架利用预先准备好的组件(例如按钮、菜单和面包屑)进行设计。

在 Tailwind CSS 中,没有准备任何组件,而是使用 Utilize Class 来创建和设计自己的组件。

# 什么是 Utilize Class

例如,如果要使用 Bootstrap 创建按钮,请将 class 设置为 btn 。
但是,在 Tailwind 中,并没有 btn 等用于创建按钮的 class,你可以通过编写如下所示的 Utilize Class 来创建按钮。你可能会觉得要设置的类太多了,但是学习成本很低,因为你一用就习惯了。如果不知道类名,可以通过搜索 Tailwind CSS 文档轻松找到它。

<button class="bg-indigo-700 font-semibold text-white py-2 px-4 rounded">
  前端晚间课
</button>
1
2
3

# 为什么选择 Tailwind CSS

使用 Tailwind CSS,你可以使用 Utilize Class 轻松设置响应式设计,因此您无需设置媒体查询。
一旦习惯了 Tailwind CSS,你就会忘记使用媒体查询。

此外,作为伪类的悬停和焦点等设置无法通过 style 属性进行设置,但在 Tailwind CSS 中,可以通过利用类设置伪类。你还可以使用 Utilize Class 通过 CSS 设置动画和渐变颜色。

# 搭建环境

# cdn

link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css"
rel="stylesheet">
1
2

请注意,如果你使用 cdn,你将无法自定义 Tailwind CSS,这将在本文档后面介绍,例如添加颜色。

# 使用 npm/yarn 安装 Tailwind css

你无法使用 cdn 自定义 Tailwind CSS。如果要自定义,需要用 npm、yarn 来安装 Tailwind CSS。

 npm init -y

 npm install tailwindcss@latest
1
2
3

接下来,创建一个 css 目录并在其中创建一个 style.css 文件。
将以下三个 tailwind 指令添加到 style.css 文件中。
这个 style.css 不能直接从 html 中读取。因此,我们稍后会构建它,并将其转换为熟悉的 html 可以读取的 css 文件。通过构建,Tailwindcss 使用的 Utilize Class 将从基础、组件和实用程序中提取。

@tailwind base;
@tailwind components;
@tailwind utilities;
1
2
3

创建一个public/css目录来存放构建后创建的 css 文件。

让我们实际构建并创建一个 css 文件,以从添加了 Tailwind 指令的 style.css 文件中读取 html。

$  % npx tailwind build ./css/style.css -o ./public/css/style.css

   tailwindcss 2.1.2

    Building: css/style.css

   ✅ Finished in 2.61 s
    Size: 3.81MB
    Saved to public/css/style.css
1
2
3
4
5
6
7
8
9

你可以看到创建的 css 文件包含普通的 CSS。由于 Twailwind 预先创建的所有 Utilize Class 都有描述,因此文件很大,行数为 50,000 或更多。

使用 npx 命令构建,可以将 build 命令添加到 package.json 文件中

"scripts": {
  "build": "tailwind build css/style.css -o public/css/style.css"
},
1
2
3

这样就完成了可以使用 Tailwind CSS 的环境搭建。

# 如何使用 Tailwind CSS

现在你已经构建了一个使用 Tailwind 的环境,请在 public 目录中创建以下 index.html 文件。使用 link 标签指定构建后的 style.css

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="css/style.css" />
    <title>Document</title>
  </head>
  <body>
    <h1>Hello Tailwind CSS</h1>
  </body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13

使用 Utilize Class 来装饰文本。设置四个实用程序类:字体大小、颜色、位置和粗细。

<h1 class="text-4xl text-green-700 text-center font-semibold">
  Hello Tailwind
</h1>
1
2
3

# 字符大小设置

要设置字体大小,请使用 text- {size}。大小可以取 13 个值。相应的 CSS 样式在括号中。

.text-xs(字体大小:.75rem;)
.text-sm(字体大小:.875rem;)
.text-base(字体大小:1rem;)
.text-lg(字体大小:1.125rem;)
.text-xl(字体大小:1.25rem;)
.text-2xl(字体大小:1.5rem;)
.text-3xl(字体大小:1.875rem;)
.text-4xl(字体大小:2.25rem;)
.text-5xl(字体大小:3rem;)
.text-6xl(字体大小:4rem;)
.text-7xl(字体大小:4.5rem;)
.text-8xl(字体大小:6rem;)
.text-9xl(字体大小:8rem;)
1
2
3
4
5
6
7
8
9
10
11
12
13

当实际应用于 html 时,它将如下所示:

<div class="text-center mt-10">
  <p class="text-xs">前端晚间课</p>
  <p class="text-sm">前端晚间课</p>
  <p class="text-base">前端晚间课</p>
  <p class="text-lg">前端晚间课</p>
  <p class="text-xl">前端晚间课</p>
  <p class="text-2xl">前端晚间课</p>
  <p class="text-3xl">前端晚间课</p>
  <p class="text-4xl">前端晚间课</p>
  <p class="text-5xl">前端晚间课</p>
  <p class="text-6xl">前端晚间课</p>
</div>
1
2
3
4
5
6
7
8
9
10
11
12

# 字符粗细设置

要设置字符粗细,请使用 font- {thickness}。厚度可以取 9 个值。相应的 CSS 样式在括号中。

.font-thin (font-weight: 100;)
.font-extralight (font-weight: 200;)
.font-light (font-weight: 300;)
.font-normal (font-weight: 400;)
.font-medium (font-weight: 500;)
.font-semibold (font-weight: 600;)
.font-bold(font-weight:700;)
.font-extrabold(font-weight:800;)
.font-black(font-weight:900;)
1
2
3
4
5
6
7
8
9
<div class="text-center mt-10">
  <p class="font-thin">前端晚间课</p>
  <p class="font-extralight">前端晚间课</p>
  <p class="font-light">前端晚间课</p>
  <p class="font-normal">前端晚间课</p>
  <p class="font-medium">前端晚间课</p>
  <p class="font-semibold">前端晚间课</p>
  <p class="font-bold">前端晚间课</p>
  <p class="font-extrabold">前端晚间课</p>
  <p class="font-black">前端晚间课</p>
</div>
1
2
3
4
5
6
7
8
9
10
11

# 文字颜色设置

要设置文本颜色,请使用 text- {color}-{color depth}。颜色可以设置为白色、黑色、红色、蓝色、靛蓝色……等。颜色强度可以取 9 个值。例如,在绿色的情况下,如下所示。

text-green-100(颜色:# f0fff4;)
text-green-200(颜色:#c6f6d5;)
text-green-300(颜色:#9ae6b4;)
text-green-400(颜色:#68d391;)
text-green-500(颜色:#48bb78;)
text-green-600(颜色:#38a169;)
text-green-700(颜色:#2f855a;)
text-green-800(颜色:#276749;)
text-green-900(颜色:#22543d;)
1
2
3
4
5
6
7
8
9

TIP

如果要将文本颜色更改为红色而不是绿色,可以像 text-red-500 一样更改它。如果要更改背景颜色,可以使用 bg-red-500 进行设置。

<div class="text-center mt-10">
  <p class="text-green-100">前端晚间课</p>
  <p class="text-green-200">前端晚间课</p>
  <p class="text-green-300">前端晚间课</p>
  <p class="text-green-400">前端晚间课</p>
  <p class="text-green-500">前端晚间课</p>
  <p class="text-green-600">前端晚间课</p>
  <p class="text-green-700">前端晚间课</p>
  <p class="text-green-800">前端晚间课</p>
  <p class="text-green-900">前端晚间课</p>
</div>
1
2
3
4
5
6
7
8
9
10
11

也可以使用诸如边距、填充和 flexbox 之类的实用程序类。您可以在官方文档中查看每个 Utilize Class

# 创建按钮

<button class="bg-indigo-700 font-semibold text-white py-2 px-4 rounded">
  前端晚间课
</button>
1
2
3

# Tailwind CSS 自定义

由于按钮是一个很有可能被重用的组件,并且你希望在应用程序中统一设计,你可以注册 Utilize Class 集来创建按钮作为另一个类

打开预构建的 css / style.css 文件并在@components 和 @utility 指令之间添加以下内容。

@tailwind base;

@tailwind components;

/* 放在这个位置,表明其属于components,应用时可被覆盖 */
.btn {
  @apply font-semibold text-white py-2 px-4 rounded;
}

@tailwind utilities;

/* 放在这个位置,这个属性将最后生成,即很难被覆盖掉 */
.btnFianl {
  @apply font-semibold text-white py-2 px-4 rounded;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

最好的方式就是显式指明其所属层级,此时无论位置在哪里,他都属于 components,即可以轻松被覆盖

@tailwind utilities;
/**
 * Use this directive to control where Tailwind injects the responsive
 * variations of each utility.
 *
 * If omitted, Tailwind will append these classes to the very end of
 * your stylesheet by default.
 */
/*@tailwind screens;*/

@layer components {
  .btnPurple {
    @apply w-72 p-4 bg-purple-waterChestnuts hover:bg-green-100 shadow-md hover:shadow-innerMd text-gray-100 hover:text-gray-500 rounded-full transition-all ease-in duration-200;
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

然后重新构建一下,npm run build,

会覆盖构建完后的 public/css/style.css,所以打开 style.css 文件,搜索 btn

可以看到刚才用@apply 添加的内容已经作为 css 添加到 style.css 文件中了,

.btn {
  font-weight: 600;
  color: #fff;
  padding-top: 0.5rem;
  padding-bottom: 0.5rem;
  padding-left: 1rem;
  padding-right: 1rem;
  border-radius: 0.25rem;
}
1
2
3
4
5
6
7
8
9

使用 btn 类和添加的按钮创建,只将背景颜色更改为红色。

<div class="text-center mt-10">
  <button class="bg-indigo-700 font-semibold text-white py-2 px-4 rounded">
    前端晚间课
  </button>
  <button class="bg-red-700 btn">前端晚间课</button>
</div>
1
2
3
4
5
6

# 伪类设置悬停

了解如何通过悬停在 Tailwind 中执行伪类,以在光标悬停在按钮上时更改按钮的颜色。如果要更改颜色,请在悬停后设置颜色,设置将可以体现出来。

<button class="bg-red-700 btn hover:bg-red-500">前端晚间课</button>
1

# 伪类设置焦点

单击按钮时还要设置焦点。为了清晰起见,从圆角变为圆形以强调按钮的圆度。修改@apply

@tailwind base;

@tailwind components;
.btn {
  @apply font-semibold text-white py-2 px-4 rounded-full;
}
@tailwind utilities;
1
2
3
4
5
6
7

当选择按钮(使用选项卡)时,将显示一个方框。单击时会出现一个方框,因此我们通过设置焦点以擦除方框。

当我将焦点设置为无轮廓时,外框消失,但我不知道按钮是否被选中。

<button class="bg-red-700 btn hover:bg-red-500 focus:outline-none">
  前端晚间课
</button>
1
2
3

设置阴影轮廓,以便您可以看到按钮被选中。如果你设置它,会沿着按钮创建一个阴影,所以用户不会感到任何不适。

<button
  class="bg-red-700 btn hover:bg-red-500 focus:outline-none focus:shadow-outline"
>
  前端晚间课
</button>
1
2
3
4
5

# 过渡设置

我确认通过设置伪类的悬停可以在光标移到按钮上时更改按钮的颜色。当光标悬停在按钮上时,你可以看到颜色。你可以通过使用过渡慢慢改变按钮的颜色。下面通过设置duration-1000,颜色会在 1 秒内缓慢变化。持续时间的多个值从duration-75duration-1000 注册。

<button
  class="bg-indigo-700 font-semibold text-white py-2 px-4 rounded hover:bg-red-700 duration-1000"
>
  前端晚间课
</button>
1
2
3
4
5

# 变换设置

如果你想让按钮本身变大并通过悬停更改按钮的颜色,您可以使用 transform 和 scaling 的 Utilize Class 来实现。

<button
  class="bg-indigo-700 font-semibold text-white py-2 px-4 rounded transform hover:scale-110 hover:bg-red-700 duration-1000"
>
  前端晚间课
</button>
1
2
3
4
5

# 群组设置

到目前为止的 hover 设置中,当光标经过目标元素时,hover 的变化就会发生在元素上,但是在 group 设置中,当光标经过父元素时,设置 hover 的子元素中就可以呈现 hover 效果。

在下面的示例中,当光标经过设置了 group 的父元素时,由于为子元素设置的悬停设置,一个 p 标签元素的文本颜色变为红色,另一个变为蓝色。

<div class="group m-10 p-10 border hover:bg-gray-100">
  <p class="font-black group-hover:text-red-900">前端晚间课</p>
  <p class="font-black group-hover:text-blue-900">前端晚间课</p>
</div>
1
2
3
4

# 动画设置

只需将 animate-bounceanimate-pulse 设置为 class,您就可以轻松设置动画,而无需设置复杂的 CSS。

# tailwind.confing.js 配置文件

# 创建配置文件

使用 Tailwind CSS,你可以通过添加 Tailwind CSS Utilize Class 中未包含的颜色、边距、宽度等进行自定义。自定义需要配置文件,但默认情况下不会创建,所以使用命令创建。

npx tailwind init

   tailwindcss 2.1.2

   ✅ Created Tailwind config file: tailwind.config.js
1
2
3
4
5

上面的命令将创建一个 tailwind.config.js 文件。

# 添加颜色

module.exports = {
  theme: {
    extend: {
      colors: {
        cyan: "#9cdbff",
      },
    },
  },
  variants: {},
  plugins: [],
};
1
2
3
4
5
6
7
8
9
10
11

即使不使用配置文件,也可以通过将颜色用括号括起来来设置应用程序中不常用的颜色,例如 bg-[#9cdbff]

添加后,构建,npm run build

将按钮颜色从红色更改为青色。由于加入青色时没有设置色深,所以设置为bg-cyan(从bg-red-700改为bg-cyan)

<button
  class="bg-cyan btn hover:bg-red-500 focus:outline-none focus:shadow-outline"
>
  前端晚间课
</button>
1
2
3
4
5

# 添加最大宽度并添加间距

你可以使用 max-width 设置浏览器上元素的最大宽度,但你可能希望将其设置为与 Tailwind CSS 中默认注册的宽度不同的宽度。在这种情况下,请在 tailwind.config.js 以及颜色中进行其他设置。

theme: {
    extend: {
        colors:{
            'cyan':'#9cdbff',
        },
        maxWidth:{
            custom:'60rem',
        },
    },
    variants: {},
    plugins: []
},
1
2
3
4
5
6
7
8
9
10
11
12

在 class 属性中使用时,设置max-w-custom

可以使用间距设置宽度

theme: {
    extend: {
        colors:{
            'cyan':'#9cdbff',
        },
        maxWidth:{
            custom:'60rem',
        },
        spacing:{
            76: '19rem',
        },
    },
    variants: {},
    plugins: []
},
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

在 class 属性中使用时,设置为w-76

即使你不使用配置文件,你也可以为那些不经常使用的样式设置一个诸如 p-[19rem]之类的描述。

# 添加字体大小

最小的字体大小类是text-xs,但是如果你想添加一个更小的字体大小类,你可以这样做。

theme: {
    extend: {
        colors:{
            'cyan':'#9cdbff',
        },
        maxWidth:{
            custom:'60rem',
        },
        spacing:{
            76: '19rem',
        },
        fontSize:{
            xxs:['0.625em',{lineHeight:'1rem'}],
        },
    },
    variants: {},
    plugins: []
},
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

如果要使用它,请在 class 属性中设置 text-xxs

# 如何自定义其他值

我解释了如何添加颜色、最大宽度、宽度和字体大小,但是当我想添加框阴影时,我应该在哪里查看设置方法

# Tailwind CSS 插件设置

# tailwindcss / line-clamp

npm install @tailwindcss/line-clamp
1

进行设置后,你将需要构建。运行 npm run build。构建完成后,使用插件的设置就完成了。

line-clamp 设置 line-clamp 后要显示的行数,如下所示。

<div class="m-20">
  <div class="line-clamp-3">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Suscipit a in ad
    voluptatem //略
  </div>
</div>
1
2
3
4
5
6

# 与 antd pro 集成

npm install -D tailwindcss postcss autoprefixer

# run the init command to generate both tailwind.config.js and postcss.config.js.
npx tailwindcss init -p
1
2
3
4
  • 修改tailwind.config.js,添加文件路径,以便编译
module.exports = {
  content: ["./src/**/*.{js,jsx,ts,tsx}"],
  theme: {
    extend: {},
  },
  plugins: [],
};
1
2
3
4
5
6
7
  • 创建存放样式 css 的目录 styles

在 src 目录(存放源码的目录) 创建 styles 目录,专门来存放样式文件的。

然后在 styles 目录里创建 tailwind.css 文件,还有 index.css 文件。

index.css 文件的内容如下:

// ./src/styles/index.css
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
1
2
3
4

或者这样:

// ./src/styles/index.css
@tailwind base;

@tailwind components;

@tailwind utilities;
1
2
3
4
5
6
  • package.json 中加入命令,以下命令生成 css 文件
    • 为什么不是自动编译生成?
"scripts": {
  "build:style": "tailwind build src/styles/index.css -o src/styles/tailwind.css",
},
1
2
3
  • 组件中引入 tailwindcss.css
    • 由于 antd 的 CSS Modules 的原因
import React from "react";
import "mui-player/dist/mui-player.min.css";
import styles from "./MyMoment.less";
import tailwind from "@/style/tailwind.css";

/**
 * 难用
 * @param props
 * @returns {JSX.Element}
 * @constructor
 */
export default function MyTainWindCss(props) {
  return (
    <main className={styles.main}>
      <section className={styles.rowSec}>
        <section
          className={`${tailwind["text-red-300"]} ${tailwind["bg-red-100"]}`}
        >
          hello tailwindcss
        </section>
      </section>
    </main>
  );
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

TIP

/* 定义全局样式 */
:global(.text) {
  font-size: 16px;
}

/* 定义多个全局样式 */
:global {
  .footer {
    color: #ccc;
  }
  .sider {
    background: #ebebeb;
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 更简洁书写,放弃 css moudles 的改造

修改配置文件 congfig.ts,注意context.resourcePath.includes('tailwind.css')这一句的添加,即不对该文件的样式进行重组

  cssLoaderOptions: {
    modules: true,
    getLocalIdent: (
      context: {
        resourcePath: string;
      },
      _: string,
      localName: string,
    ) => {
      if (
        context.resourcePath.includes('node_modules') ||
        context.resourcePath.includes('ant.design.pro.less') ||
        context.resourcePath.includes('global.less') ||
        context.resourcePath.includes('tailwind.css')
      ) {
        return localName;
      }

      const match = context.resourcePath.match(/src(.*)/);

      if (match && match[1]) {
        const antdProPath = match[1].replace('.less', '');
        const arr = slash(antdProPath)
          .split('/')
          .map((a: string) => a.replace(/([A-Z])/g, '-$1'))
          .map((a: string) => a.toLowerCase());
        return `antd-pro${arr.join('-')}-${localName}`.replace(/--/g, '-');
      }

      return localName;
    },
  },
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

此时可轻松书写 class

<main
  className={`${themeType} flex flex-wrap items-center gap-x-8 p-4 bg-indigo-200/50`}
></main>
1
2
3

# 关于自动编译css文件

新增以下脚本,区分开发与打包编译

    "dev:style": "tailwind build -i ./src/style/index.css -o src/style/tailwind.css --watch",
    "build:style": "tailwind build -i ./src/style/index.css -o src/style/tailwind.css --minify"
1
2

终端执行命令yarn dev:style,即可实时跟踪css文件的变更进行自动编译转换

为了减少不必要的编译,还可以做出限制,即调整tailwind.config.js,即content字段的内容

const myColors = require('./src/constant/MyColors');

module.exports = {
  content: ['./src/pages/plugin/**/*.{js,jsx,ts,tsx}'],
1
2
3
4