tailwindcss 分享

891 阅读5分钟

1. 基本介绍

image.png

与公司私有包 @yige/base 类似

2. 优势

  1. 不用在页面上来回跳转
  2. 不用在样式名上面花费太多的时间;
  3. 极大的节省打包体积;
  4. 对比@yige/base
    • 有专门的团队维护,包含的样式更加全面;
    • 可以只打包引入的那些样式;
    • 结合vscode的 Tailwind CSS IntelliSense 可以做到自动提示;
  5. 对比行内样式
    • 行内样式会造成最终的打包内容很大;
    • 行内样式无法使用 hover、focus等其他状态,无法使用媒体查询、伪类、伪元素等等

3. 使用

3.1 vscode 配置

vscode 安装 Tailwind CSS IntelliSense 插件, 在vscode的settings里面设置

"files.associations": {  
    "*.css": "tailwindcss"  
},
"editor.quickSuggestions": {  
    "strings": true  
}

3.2 项目配置

3.2.1 tailwind.config.js

在根目录下创建 tailwind.config.js

/** @type {import('tailwindcss').Config} */

module.exports = {
  content: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}'], // 设置tailwind有效的路径
  theme: { extend: {}, }, 
  plugins: [],
}

3.2.2 安装 prettier-plugin-tailwindcss,

格式化调整顺序

prettier.js 添加如下内容

module.exports = {
  // ....
  plugins: [require("prettier-plugin-tailwindcss")], // 如果是pnpm、yarn 就需要手动引入,npm 是自动引入
  tailwindConfig: "./tailwind.config.js",
}
3.2.3 vite中配置postcss

安装 autoprefixer, npm i autoprefixer -D。 在 vite.config.ts中添加

css: {
    postcss: {
        plugins: [require('tailwindcss'), require('autoprefixer')], // vite 默认支持 postcss-import
    },
},

3.3 开始使用

3.3.1 引入
  1. 安装 tailwindcss
npm i tailwindcss

2. 创建 style/tailwind.css

@tailwind base; // 引入基础样式,用于重置浏览器的默认样式、设置盒模型和其他一些全局的样式规范。对应 src/css/preflight
@tailwind components; // 引入组件样式,提供的预定义组件样式,并在项目中直接应用这些样式。
@tailwind utilities; // 这个指令用于引入工具类样式,工具类是一组独立的、单一目的的样式类,用于提供快速且灵活的样式控制
  1. main.js 中引入
import "./styles/tailwind.css"

或者直接引入 import "tailwind/tailwind.css" ,里面已经包含了上面三个选项

3.3.2 base/components/utilities

遵循 ITCSS 规范
base:处理html的默认样式
components: 对utilities的进一步封装
utilities:具有单个目的样式,原子化

@layer、@apply
@layer 指明添加一组自定义样式属于 basecomponents 还是 utilities,将失去 !important
@apply 将已有的类添加到自定义css

@tailwind base;
对一些基本样式进行初始化,消除浏览器不通过带来的差异

// 自定义基础样式
@layer base {
  h1 {
    @apply text-2xl;
  }
  h2 {
    @apply text-xl;
  }
  :root { // 定义一些css变量
    --color-primary: rgb(255 115 179);
    --color-secondary: rgb(111 114 185);
    /* ... */
  }
}

@tailwind components;
通过对 utilities 进行组合,最终形成一系列组件样式

@layer components {
   .btn-blue {
     @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和直接定义全局class的区别,可以通过@apply引入其他的tailwind定义的样式,可以自动完成 tree-shaking

注意:不要滥用css组件,更多的利用 vue 的组件化会更有效

@tailwind utilities;
用于引入工具类样式。工具类是一组独立的、单一目的的样式类,用于提供快速且灵活的样式控制。这个必须要引入,否则 tailwindcss 里面的基础样式将无法生效(这些样式就是一些独立的自定义样式类)

// 自定义工具类
@layer utilities {
  .filter-none {
    filter: none;
  }
  .filter-grayscale {
    filter: grayscale(100%);
  }
}
3.3.3 在组件里面自定义 @layer components
<style scoped>
/* 这儿不要引入含有tailwindcss/base的路径,会导致base里面杯重复打包进css */
@import url('tailwindcss/components'); /*这个引入也是必须的 */
@layer components {
    .btn-blue {
        @apply rounded-lg bg-blue-500;
    }
}
</style>

如果要在vue组件里面通过@apply使用全局设置自定义components样式,只能通过插件的方式

// tailwind.config.js
const plugin = require('tailwindcss/plugin')
 plugins: [
    plugin(function ({ addComponents, theme }) {
      addComponents({
        '.card': {
          backgroundColor: 'red',
        },
      })
    }),
 ],

plugin 函数暴露的参数还包括下面这些

3.3.4 构建 tailwindcss
  1. 如果是自己使用postcss,配置如下
// postcss.config.js
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
    ...(process.env.NODE_ENV === 'production' ? { cssnano: {} } : {})
  }
}
  1. 如果使用的是 vite,已经处理完毕,只会打包引入的内容。
3.3.5 各种状态示例
  1. hover、focus、active
<button class="bg-violet-500 hover:bg-violet-600 active:bg-violet-700 focus:outline-none focus:ring focus:ring-violet-300 ...">Save changes</button>
  1. first、last、odd、and even
<ul>
  <li class="first:bg-red-100 last:bg-blue-500 v-for="item in 5"></li>
</ul>

<ul>
  <li class="odd:bg-white even:bg-slate-50" v-for="item in 5"></li>
</ul>
  1. before and after
<span class="after:content-['*'] after:ml-0.5 after:text-red-500">Email</span>
3.3.6 暗黑模式

tailwind.config.js 里面设置

module.exports = {
    darkMode: 'class'
}

添加暗黑模式的样式

<div class="test dark:bg-red-800"></div>

然后只要控制 html 的样式就可以切换暗黑模式

// 给 html 添加 dark 的 class 类
document.documentElement.classList.add('dark')

自定义触发方式

module.exports = {
    darkMode: ['class', '[data-mode="dark"]'],
}

当该<div>元素上添加了data-mode="dark"属性时,Tailwind CSS会应用暗黑模式的样式规则

<div data-mode="dark">
  <!-- 这里是暗黑模式下的内容 -->
</div>

注意:当 darkMode 设置为 class 的时候只能作用 html 元素才有效。

3.3.7 自定义主题
// tailwind.config.js
// 获取默认的主题设置
const defaultTheme = require('tailwindcss/defaultTheme')
// 获取默认的颜色
const colors = require('tailwindcss/colors')
module.exports = {
  theme: {
    screens: {
      // 会直接覆盖
      sm: '480px',
      md: '768px',
      lg: '976px',
      xl: '1440px',
    },
    extend: {
      // 扩展
      colors: {
        // 展一个主题颜色,使用 <div class="bg-white text-primary">
        primary: 'red', 
      },
    },
  },
}
3.3.8 使用任意数字值
// 自定义宽高
<div class="h-[100px] w-[10rem] bg-blue-200"></div>

使用 important,在前面加上 !

<div class="!h-[100px] w-[100px] bg-blue-200"></div>
3.3.9 tailwind 提供的方法

注意由于预处理器lessscssstylus是在tailwindcss之前被解析,所以不要在里面使用 theme() 或者 screen() 方法

  1. theme()

可以通过.表示法访问 tailwind 配置表

.content-area {
  height: calc(100vh - theme(spacing.12));
}

访问嵌套颜色值时不要使用短划线语法

background-color: theme(colors.blue-500);
==>
background-color: theme(colors.blue.500);

调整颜色不透明度,使用 /

background-color: theme(colors.blue.500 / 75%);
  1. screen()
@media screen(sm) {
/* ... */
}
// 等价于
@media (min-width: 640px) {
/* ... */
}
3.3.10 tailwindcss 里面的 space

数值 4 对应的是1rem

mt-4 /* 单位4对应的是1rem,默认情况下1rem为16px */

接下来就是熟悉 tailwindcss 里面提供的样式了。