Tailwind 基础教程

2021-05-05
css
约 3249 字 预计阅读 7 分钟

Tailwind是一个现代的css框架,集合了大多数常用的规范化的类,它们能直接在脚本标记语言中组合起来,构建出任何设计,即使你不会css,也能轻松的用它来构建html页面或者网站, 不同于bootstrap,bootstrap提供的是组件,tailwind不提供任何组件,它提供的是:

  • 碎片的包装好的常用样式,这些样式的名称的非常简短,大大简化了样式的代码量
  • 无论颜色,长度,粗细,宽高,margin,padding等等都有数字或者分数写好的类,比如宽度w-96 w-5/6 w-full
  • 有些样式可以和响应式的breakpoint进行组合(这也是为什么tailwind文件有点大的原因,排列组合太多了),比如sm:w-20 lg:w-40

最近没事看了看最新版本的bootstrap,发现已经和tailwind靠拢了(太久没用过了,上一次用可能是在7年前了),所以tw和bs现在都可以使用

1. 快速开始

1.1. 安装方式介绍

我把tailwind的使用方式(不包含前端集成框架如vue,react之类的)分为下面几种:

  • 页面上直接使用tailwind的类,在html里引入(css)
  • 导入tailwind,然后在样式表里用@apply进行开发,最后用tailwindcss-cli一起编译,然后在html里引入(css)
  • 用sass开发样式表,在工具链里(含有postcss)加入postcsstailwind插件或者用postcsspostcss-import插件导入(sass)

1.1.1. 直接在html里引入

这种方式最为简单,直接上jsdelivr之类的cdn找个tailwindcss的min的<link>复制到自己的html上就行

或者用npx tailwindcss-cli@latest build -o tailwind.css自己编译一个,再加到html上

这种方式比较开放,也最简单,但是使用场景比较少,用在特别简单的项目,用传统方式开发的(无脚手架和工具链)

1.1.2. 自定义样式用tailwindcss-cli编译

这种方式可以理解为将tailwindcss进行自定义之后,再进行编译,比如:

在tailwind的基础上进行修改或者写上自己的样式之后

1
2
3
4
5
6
7
8
9
/* ./src/tailwind.css */
@tailwind base;
@tailwind components;

.btn {
  @apply px-4 py-2 bg-blue-600 text-white rounded;
}

@tailwind utilities;

tailwindcss-cli编译

1
npx tailwindcss-cli@latest build ./src/tailwind.css -o ./dist/tailwind.css

这种方式,页面上也可以直接用tailwind的类

1.1.3. 结合打包工具链和postcss的使用

如果工具链上有postcss,那么处理起来就很方便,这也是官方推荐的方式.

方法一: 使用postcss-import插件

配置postcss, 注意这种方式其实不需要添加tailwindcss插件了

 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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// 一个普通的postcss.config.js配置方式
const themeDir = __dirname + "/../../";

module.exports = {
  plugins: [
    require("postcss-import")({
      path: [themeDir],
    }),
    require("tailwindcss")(themeDir + "assets/css/tailwind.config.js"),
    require("autoprefixer")({
      path: [themeDir],
    }),
  ],
};

// 或者
module.exports = {
  plugins: {
    'postcss-import': {},
    tailwindcss: {},
    autoprefixer: {},
    // other plugins can go here, such as autoprefixer
  },
};


// rollup里配置的postcss
import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import scss from "rollup-plugin-scss";
import autoprefixer from "autoprefixer";

import postcss from "postcss";
import atImport from "postcss-import";
import tailwindcss from "tailwindcss";

const isProduction =
  process.env.NODE_ENV === "production" || process.env.BUILD === "production";

export default (async () => ({
  input: "src/js/main.js",
  output: {
    file: "public/js/bundle.js",
    format: "iife",
    sourcemap: true,
    globals: {
      jquery: "$",
    },
  },
  external: ["jquery"],
  plugins: [
    resolve(), // Tells Rollup how to find date-fns in node_modules
    commonjs(), // Convert CommonJS modules to ES Modules.
    isProduction && (await import("rollup-plugin-terser")).terser(),
    scss({
      output: "public/css/bundle.css",
      sass: require("sass"),

      processor: (css) =>
        postcss([
          autoprefixer({ overrideBrowserslist: "Edge 18" }),
          tailwindcss(),
        ])
          .use(atImport())
          .process(css, { from: undefined })
          .then((result) => result.css),
      // Add file/folder to be monitored in watch mode so that changes to these files will trigger rebuilds.
      // Do not choose a directory where rollup output or dest is pointed to as this will cause an infinite loop
      watch: "src/sass",
      // watch: ["src/styles/components", "src/multiple/folders"],
    }),
  ],
}))();

这样就可以在样式文件里,随时随地的引入(最好在入口文件引入一次就行)

1
2
3
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";

如此配置,其它样式文件里可以@apply来使用tailwind的样式, 同时tailwind也被编译合并到我们的入口文件中,在页面上的class也可以使用

方法二: 使用tailwindcss插件

差别不大,目的都是为了在我们的样式表里可以直接使用tailwind

在任意的css文件里添加引入tailwind的组件, 如果是合并所有css文件的编译,则页面上不需要单独引入, 如果不是合并编译,则需要在页面上单独用<link>引入

1
2
3
4
/* ./your-css-folder/styles.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

1.2. 最基本的安装和使用

新建一个项目,然后用npm初始化

1
npm init -y

使用npm安装进行安装

1
npm install -D tailwindcss@latest postcss@latest autoprefixer@latest

将Tailwind添加为PostCss的插件,新建postcss.config.js

1
2
3
4
5
6
7
// postcss.config.js
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  }
}

创建tailwind的配置文件

1
npx tailwindcss init

内容如下

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// tailwind.config.js
module.exports = {
  purge: [],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {},
  plugins: [],
}

引入基本的tailwind库,创建一个css文件,比如/styles/style.css

1
2
3
4
/* ./your-css-folder/styles.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

如果有其它打包工具,可以用import的形式引入,例如postcss开启了postcss-import插件

1
2
3
@import "node_modules/tailwindcss/base";
@import "node_modules/tailwindcss/components";
@import "node_modules/tailwindcss/utilities";

打包命令,可以写到package.json里

1
2
3
postcss styles/style.css -o public/css/tailwind.css
或者
npx tailwindcss build src/styles/style.css -o public/css/tailwind/css

然后就可以在html里引入(public/index.html)

1
<link ref="stylesheet" href="css/tailwind.css">

1.3. 直接在浏览器使用

如果你不想集成打包(可以在自己的样式文件里使用),而只是简单的在页面上使用

2. 布局相关

2.1. Display

Class Properties
block display: block;
inline-block display: inline-block;
inline display: inline;
flex display: flex;
inline-flex display: inline-flex;
table display: table;
inline-table display: inline-table;
table-caption display: table-caption;
table-cell display: table-cell;
table-column display: table-column;
table-column-group display: table-column-group;
table-footer-group display: table-footer-group;
table-header-group display: table-header-group;
table-row-group display: table-row-group;
table-row display: table-row;
flow-root display: flow-root;
grid display: grid;
inline-grid display: inline-grid;
contents display: contents;
list-item display: list-item;
hidden display: none;

2.2. Flex布局的重点

flex在css里分为容器属性和项目属性2种 容器属性有

  • flex-direction
  • flex-wrap
  • flex-flow
  • justify-content
  • align-items
  • align-content

项目属性

  • order
  • flex-grow
  • flex-shrink
  • flex-basis
  • flex
  • align-self

Flex

Class Properties
flex-1 flex: 1 1 0%;
flex-auto flex: 1 1 auto;
flex-initial flex: 0 1 auto;
flex-none flex: none;

flex在css里有3个值,分别是flex-grow,flex-shrinkflex-basis,tw里的flex是一个简写形式

  • flex-basis是项目在分配多余空间之前的大小, 可选的值有0%, 300px, auto
  • flex-grow 是否拉伸 01
  • flex-shrink 是否缩小 01

Flex Direction 方向

Class Properties
flex-row flex-direction: row;
flex-row-reverse flex-direction: row-reverse;
flex-col flex-direction: column;
flex-col-reverse flex-direction: column-reverse;

Flex Shrink item是否会被压缩

Class Properties
flex-shrink-0 flex-shrink: 0;
flex-shrink flex-shrink: 1;

Flex Grow item是否会可以拉伸

Class Properties
flex-grow-0 flex-grow: 0;
flex-grow flex-grow: 1;

Flex Wrap 换行属性

Class Properties
flex-wrap flex-wrap: wrap;
flex-wrap-reverse flex-wrap: wrap-reverse;
flex-nowrap flex-wrap: nowrap;

Order 排序 示例: order-2 可选值有1到12,first,last, none

Justify Content

在主轴方向的对齐

Class Properties
justify-start justify-content: flex-start;
justify-end justify-content: flex-end;
justify-center justify-content: center;
justify-between justify-content: space-between;
justify-around justify-content: space-around;
justify-evenly justify-content: space-evenly;

align-items

在交叉轴上的对齐方式,tw里的属性如下

Class Properties
items-start align-items: flex-start;
items-end align-items: flex-end;
items-center align-items: center;
items-baseline align-items: baseline;
items-stretch align-items: stretch;

Align Content

多主轴的时候交叉轴对齐方式在单主轴下无效

Class Properties
content-center align-content: center;
content-start align-content: flex-start;
content-end align-content: flex-end;
content-between align-content: space-between;
content-around align-content: space-around;
content-evenly align-content: space-evenly;

Align Self

单个item自己的交叉轴对齐方式,脱离父flex元素的对齐方式

Class Properties
self-auto align-self: auto;
self-start align-self: flex-start;
self-end align-self: flex-end;
self-center align-self: center;
self-stretch align-self: stretch;

2.3. 内置的方法和指令

see: Functions and Directives

@tailwind

用来引入tailwind的几组集成样式base, components, utilities and screens

 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
/**
 * This injects Tailwind's base styles and any base styles registered by
 * plugins.
 */
@tailwind base;

/**
 * This injects Tailwind's component classes and any component classes
 * registered by plugins.
 */
@tailwind components;

/**
 * This injects Tailwind's utility classes and any utility classes registered
 * by plugins.
 */
@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;

@apply

当自定义class的时候,@apply可以用来引用tw定义好的class

1
2
3
4
5
6
.btn {
  @apply font-bold py-2 px-4 rounded;
}
.btn-blue {
  @apply bg-blue-500 hover:bg-blue-700 text-white;
}

@apply会移除!important

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
/* Input */
.foo {
  color: blue !important;
}

.bar {
  @apply foo;
}

/* Output */
.foo {
  color: blue !important;
}

.bar {
  color: blue;
}

@layer

用来指定tw的集合几乎用不到

 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
@tailwind base;
@tailwind components;
@tailwind utilities;

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

@layer components {
  .btn-blue {
    @apply bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded;
  }
}

@layer utilities {
  @variants hover, focus {
    .filter-none {
      filter: none;
    }
    .filter-grayscale {
      filter: grayscale(100%);
    }
  }
}

@variants

1
2
3
4
5
6
7
8
@variants focus, hover {
  .rotate-0 {
    transform: rotate(0deg);
  }
  .rotate-90 {
    transform: rotate(90deg);
  }
}

将会生成

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
.rotate-0 {
  transform: rotate(0deg);
}
.rotate-90 {
  transform: rotate(90deg);
}

.focus\:rotate-0:focus {
  transform: rotate(0deg);
}
.focus\:rotate-90:focus {
  transform: rotate(90deg);
}

.hover\:rotate-0:hover {
  transform: rotate(0deg);
}
.hover\:rotate-90:hover {
  transform: rotate(90deg);
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
/* Input */
@variants hover, focus {
  .banana {
    color: yellow;
  }
}

/* Output */
.banana {
  color: yellow;
}
.hover\🍌hover {
  color: yellow;
}
.focus\🍌focus {
  color: yellow;
}

3. 参考

文章作者 : Cocding