tailwindcss 从0到1

931 阅读1分钟

简介

Tailwind CSS 是一个功能类优先的 CSS 框架,它集成了诸如 flexpt-4text-center 和 rotate-90 这样的的类,它们能直接在脚本标记语言中组合起来,构建出任何设计

简单的理解 tailwind css 是原 atom css 的升级版,提供更灵活的配置, 更系统的预设样式类, 更完整的配置体系

简单例子

image.png

<div class='card w-56 h-72 px-4 rounded-md bg-white'>
    <div class='h-56 flex justify-center align-center'>
      <img class='h-full' 
      src='https://hbimg.huabanimg.com/dedfb3c6331d28a7702cf071e46650d6a7d68a75721e2-K7Ndig'
      />
    </div>
    <div class='bg-white'>
      <h2 class='text-sm text-gray-400'> Houseplant </h2>
      <div class='flex justify-between align-center'>
        <h1 class='text-lg text-black'> Anthurium </h1>
        <button class='text-center text-sm text-white py-1 px-4 bg-green-500 rounded-full'> $28.00 </button>
      </div>
    </div>
  </div>

安装

  1. 安装依赖
// vue vite
npm install tailwindcss@latest postcss@latest autoprefixer@latest
  1. 生成配置文件
npx tailwindcss init
  1. 引入样式文件
// 模式1: 通过css文件按需引入
// index.css


@tailwind base; // 基础预设样式
@tailwind components; // 组件样式
@tailwind utilities; // 工具样式
// main.js
import './index.css'
// 模式2: CND
// index.html
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
// 模式3: 全引入
import "tailwindcss/tailwind.css"

功能

个人总结 tailwind css 功能主要包括三部分:

  1. 预设样式类 prefilght
  2. 自定义扩展函数与指令 @tailwind
  3. 自定义主题,功能扩展 tailwind.config.js

预设样式类

tailwind css 提供了一套以移动优先的,响应式样式类, 类似原bootstrap 可直接使用

直接使用样式类

<button class='
m-10
w-24
h-12
border
rounded-full
bg-green-500
text-center
text-gl 
text-white 
font-medium'>
 按钮
</button>

image.png

类型或状态修饰

tailwind css 为处理响应式,伪类, 伪元素提供类型作用范围限定类

// 添加响应式样式
// 默认字体大小为 text-base, 当视图宽度为 sm '@media (min-width: 640px)' 字体尺寸为 text-sm
<div class='text-base sm:text-sm'> 内容 </div>


// 添加悬停样式
<div class='hover:bg-green-500 hover:text-white'> 内容 </div>


// 伪元素 
<ul>
  <li class='first:text-gray-300> item </li>
  ...
<ul>


// 黑暗模式
<div class='dark:text-white'> 内容 </div>

样式扩展

样式扩展,使我们能组合现有基础类或定义自己的样式类.

// 基础样式
// 类似 reset.css 为原始标签提供初始样式
@layout base{
  h1 {
    @apply text-2xl; // 指令 @apply 类似scss @include 收集已定义的样式类
  }
}
<h1> ... </h1>


// 抽取组件类
@layout components{
  .loc-button {
    @apply py-1 px-4 bg-black text-sm hover:bg-green-500 hover: text-whirte
  }
}


<div class='.loc-button'> ... </div>


// 功能类
@layout utilities {
  .center {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
<div class='center> ... </div>

组件类与功能类的主要区别在于职能应用场景的不同, 组件注重样式的集合和封装, 功能注重某一点只能的样式复用

函数与指令

@tailwind 用于引入样式类

  • base 基础样式类
  • components 组件样式类
  • utilities 工具样式
  • screens 媒体查询断点样式
@tailwind base;
@tailwind components;
@taiwind utillities;
@taiwind screens;

@apply 内联功能样式

.btn{
  @apply bg-blue-500 text-white;
}

@layer 划归类的分组

@layer utilities{
  .title{
    color: red;
  }
}


@layer components{
  .title{
    color: orange;
  }
}


@layer base {
  .title {
    color: blue;
  }
}
// 这里title 颜色为红色, 不同的分组将影响类的优先级顺序

@variants 指定各状态类变体

@variants hover {
  .btn {
      background: orange;
      color: white;
  }
}
// 生成样式
.btn{
   background: orange;
   color: white;
}


.hover:btn:hover{
   background: orange;
   color: white;
}
<div class='hover:btn'> ... </div>


// : 是转义的意思, 等价 scss: .hover:btn{ &:hover{ ... } }

@responsive 生成默认响应式类变体

@responsive{
  .bg-color{
     background: orange;
  }
}
// 生成样式类
@media (min-width: 640px) {
  .sm:bg-color { // 等价类名 .sm:bg-color
    background: orange;
  }
}
@media (min-width: 640px) {
  .md:bg-color { // 等价类名 .md:bg-color
    background: orange;
  }
}
... 

该指令会根据默认响应设置,为每个断点生成样式类

@screen 生成指定响应断点的变体

@screen sm{
  .bg-color{
    background: orange;
  }
}


// 生成代码
@media (min-width: 640px) {
  .sm:bg-color {
    background: orange;
  }
}

该指定只为指定的断点,生成样式类

@theme() 获取主题样式

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

定制化

通过taildwind.config.js 配置文件,能实现更多自定义功能

配置主要分为:

  • theme 主题 定制字体,颜色等视觉定义
  • variants  状体修饰定义
  • plugins 引入外部定义js 样式插件
  • presets 自定义基础类, 替代 tailwind 的默认基础类 base
  • prefix 类前缀, 可添加自定义类前缀,方式与其他样式库冲突
  • corePlugins 按需设置需要的生成类, 优化包体积

主题


  theme: {
    // 设置响应断点
    screens: {
      sm: '480px',
      md: '768px',
      lg: '976px',
      xl: '1440px',
    },
    // 调色盘
    colors: {
      gray: colors.coolGray,
      blue: colors.lightBlue,
      red: colors.rose,
      pink: colors.fuchsia,
    },
    // 间距
    spacing: {
      '1': '8px',
      '2': '12px',
      '3': '16px',
      '4': '24px',
      '5': '32px',
      '6': '48px',
    }
  },

插件

const plugin = require('tailwindcss/plugin')  
plugins: [
    
    // 定义功能类
    plugin(({ addUtilities }) => {


      const utilities = {
        '.center': {
          'display': 'flex',
          'justify-content': 'center',
          'align-items': 'center' 
        }
      }
      addUtilities(utilities, ['responsive', 'hover'])
    }),


    // 定义组件类
    plugin(({ addComponents }) => {
      const component = {
        '.btn': {
          'padding': '8px 16px',
          'border': '1px solid #eee'
        }       
      }
      addComponents(component)
    }),


    // 定义基础类
    plugin(({ addBase }) => {
      addBase({
        'h1': { fontSize: '32px' },
        'h2': { fontSize: '24px' },
        'h3': { fontSize: '18px' },
      })
    },


    // 转义
    // 如果类名中存在特殊字符时,通过 e 函数做统一转义, 例如: .hover:btn -> .hover:btn
    plugin(({ addUtilities, e }) => { addUtilities({ [`.${e('hover:btn')}`]: {...} }) }),
    
    // 前缀
    // 为类名添加自定义前缀
    // prefix: 'loc'
    plugin(({ addComponents, prefix }) => {
       addComponents({
          [prefix('.cmp')]: {...} // .loc-cmp
       })
    })
  ...
  ]

预设

module.exports = {
  presets: [
    // 导入外部自定义配置
    require('./self-tailwind-config.js')
  ],
  // ...
}

预设类名的使用

tailwind css 提供的预设类很多,一般根据官方文档,按照功能查询所需的类名。

总结几条规则:

  1. 以具体的css属性名或简写开头: flex, justify-center, p-0, m-0

  2. 尺寸:

    1. 带别名: 一般与响应式有关, text-xs, text
    2. 0.5的倍数: w-0 w-0.5 h-0 h-0.5
    3. 5倍数: placeholder-opacity-0, placeholder-opacity-5 , opacity-0, opacity-5
    4. 递增: delay-75, delay-100, delay-200
  3. 位置: border-t-0, border-r-0

总结

个人觉得 tailwind css 的主要优势在于提供了一套自定义样式模板的工具,并有一个完整的可扩展的基础示例预设样式

非常适合有UI设计体系或要求统一UI视觉的产品, 通过组合基础样式模板,统一样式规范,提高编写效率。

如果UI本身就没有统一规范的化,还是内联样式文件来的灵活些。

这一套有点像组件库为了可配置主题而抽离出来的组件样式变量。

参考

官方文档