Skip to content

对于tailwind css 的使用说明

什么是tailwindcss

tailwindcss 是一个用于快速构建用户界面的 CSS 框架。


WARNING

官方文档写得太过笼统
注意:此文档是写项目时顺手写的,用到哪写到哪,无法映射全部


安装||使用

vite项目

  1. 安装tailwindcss
bash
npm install tailwindcss @tailwindcss/vite

2.在vite.config.ts/js中导入

ts
...
import tailwindcss from '@tailwindcss/vite'
export default defineConfig({
  plugins: [
    ...,
    tailwindcss(),
  ],
})

3.在全局css中引入

css
@import "tailwindcss";

4.配置自定义css

css
@theme {
  --color-danger: #dc3545;
}
template
<div class="text-danger">hello vue</div>

普通html项目

1.使用cdn引入tailwindcss

html
 <script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>

2.配置自定义css

html
<!doctype html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
    <style type="text/tailwindcss">
      @theme {
         --color-danger: #dc3545;
      }
    </style>
  </head>
  <body>
    <h1 class="text-3xl font-bold underline text-clifford">
      Hello world!
    </h1>
  </body>
</html>

常用指令

@theme

创建自定义 CSS 变量。

css
@theme{
    --color-danger: #dc3545;
}

theme()

在 CSS 中访问 Tailwind 配置的主题值。

css
.custom-button {
  background-color: theme('colors.blue.500');
  padding: theme('spacing.4') theme('spacing.8');
  border-radius: theme('borderRadius.lg');
  font-size: theme('fontSize.lg');
}

@apply

将多个 Tailwind CSS 工具类组合成一个可复用的组件类。

css
.btn-primary {
  @apply py-2 px-4 bg-blue-500 text-white font-semibold rounded-lg shadow-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-opacity-75;
}

@layer

控制自定义样式在 Tailwind 的层叠顺序(base、components、utilities)。

层名称描述
base用于定义基础样式,如字体、颜色、边框、阴影等。
components用于定义组件样式,如按钮、导航栏、表单等。
utilities用于定义工具类样式,如 margin、padding、border、background 等。
css
@layer base {
  h1 {
    @apply text-2xl font-bold mb-4;
  }
  body {
    @apply bg-gray-100 text-gray-900;
  }
}

@responsive

读取 tailwind.config.js 中配置的断点(如 sm、md、lg),为内部的每个类自动生成「断点前缀 + 类名」的变体。

css
@layer components {
  @responsive {
    /* 自定义卡片组件,支持 sm:card / md:card 等 */
    .card {
      @apply bg-white rounded-lg shadow-md p-4;
    }
    /* 响应式按钮尺寸 */
    .btn-lg {
      @apply py-3 px-6 text-lg;
    }
  }
}
html
<button class="btn sm:btn-lg">提交</button>
<div class="card md:card p-6">业务卡片</div>

@screen

创建针对特定断点的媒体查询。

css
@screen sm {
  .sidebar {
    width: 250px;
  }
}

@screen md {
  .sidebar {
    width: 300px;
  }
}

@screen lg {
  .sidebar {
    width: 350px;
  }
}

常用class名称

这是我的个人文档