Tailwind CSS 基本使用

221 阅读4分钟

tailwindcss 的优势

It's fast, flexible, and reliable — with zero-runtime.

  • fast: 只需在页面中写类名就可以快速得到对应的样式,直观且直接
  • flexible:不需要的样式直接移除对应的类名即可,不满足的直接更改对应或移除的类名,代码迁移的时候不需要考虑层级的影响
  • reliable: github.com/tailwindlab… start截止当前高达 81.8k
  • 学习成本低、搜索文档即可解决问题

安装

必备插件Tailwind CSS IntelliSense,安装根据官网或者你所使用的前端框架文档即可:

image.png

  • 前端框架 umi 安装 tailwindcss
# 安装 Tailwindcss 所需要的依赖,然后生成需要的文件
npx umi g tailwindcss

安装成功后会通常会生成两个文件 tailwind.csstailwind.config.js

  • tailwind.css
/* eslint-disable */
@tailwind base; # 基本样式,做一些初始化,保证浏览器基本样式一致
@tailwind components; # 组件样式
@tailwind utilities;  # 工具样式
  • tailwind.config.js 很显然这就是有关 tailwind 的配置文件了,如果要扩展或者更改 tailwind 的样式就从这个文件下手了

根据 className 组装你的 style

也许刚开始看 tailwind 的人认为 学习有成本,但其实 tainwindcss 的命名和我们一样,都是"简单",“相关”而命名的,就好比我们记 “阿尔伯特·爱因斯坦” 就叫 “爱因斯坦” 一样

  • 原子类名组装, 如 bg-blue-500 text-white
  • 插槽组装, 如 text-[#f00] left-[88px]
// react file
{/* 
const dataOfMaster = {
  name: '袁天罡',
  age: 300,
  friends: ['李淳风', '李世民', '武则天'],
  alias: '不良帅、大帅',
  identity: '不良人天魁星、藏兵谷谷主',
  deathReason: '自身求死暗中加持李星云自愿被李星云杀死',
  deathPlace: '李星云的地下城',
  deathTime: '2010-01-01 12:00:00',
}; */}

<div className=" mt-4 grid grid-cols-1 sm:grid-cols-2 w-full h-full md:grid-cols-3 lg:grid-cols-4 gap-2">
    {Object.entries(dataOfMaster).map(([key, value]) => {
      return (
        <div key={key} className=" flex gap-1">
          <span className=" text-gray-500 capitalize">{key}:</span>
          <span className=" text-black line-clamp-1">{value}</span>
        </div>
      );
    })}
</div>

以上代码呈现的效果 image.png

定义 tainwind 的配置

在大多数情况下,我们或许需要结合项目的主题风格来开发,这个时候可以扩展 or 覆盖 tailwind 主题来满足这些场景,在项目根目录下的 tailwind.config.js 进行配置即可。自定义配置传送门

  • content 定义 包含 tailwind css 的文件路径
  • colors 配置应用于主题颜色,比如 text-purple,这里 purple 就是来自于 colors 下的 purple, bg-gray-light 会命中于 colors 下的 gray-light 配置
  • screens 配置应用于屏幕媒体查询的尺寸
  • spacing 配置应用于 margin, padding 的场景
  • extend 在 tailwind 的默认配置下进行扩展
// tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ['./src/**/*.{html,tsx}'], # 定义 包含 tailwind css 的文件路径
  theme: {
    colors: { 
      'blue': '#1fb6ff',
      'purple': '#7e5bef',
      'pink': '#ff49db',
      'orange': '#ff7849',
      'green': '#13ce66',
      'yellow': '#ffc82c',
      'gray-dark': '#273444',
      'gray': '#8492a6',
      'gray-light': '#d3dce6',
    },
    fontFamily: {
      sans: ['Graphik', 'sans-serif'],
      serif: ['Merriweather', 'serif'],
    },
    extend: {
      spacing: {
        '8xl': '96rem',
        '9xl': '128rem',
      },
      borderRadius: {
        '4xl': '2rem',
      }
    }
  },
}

配置注意事项

  • theme 如果没有使用 extend 则为覆盖 配置
theme: {
    colors: {
      'kj-green': 'green',
      // 会覆盖 tailwind 默认的 red 配置, 这样 text-red-500 就失效了!!
      red: '#f00',
    },
    screens: {
      sm200: '200px'
    }
  },
  • screenscolors 支持嵌套配置
theme: {
    colors: {
      'kj-green': 'green', # 使用的时候就是 text-kj-green or bg-kj-green
      // 会覆盖 tailwind 默认的 red 配置, 这样 text-red-500 就失效了!!
      red: '#f00',
    },
    screens: {
      sm200: '200px'
    }
  },

实现类名的复用

使用 @apply 抽取类名进行封装 抽取的好处是省去了重复的类名,但是坏处也有许多,抽取之前可以参考 [避免过早抽象样式](Avoiding premature abstraction,就我而言,抽取之后还有这么一些坏处

  • hover 上去没有提示
  • 名字抽象不容易理解
# component file
  <div className=" w-full h-full bg-indigo-300 ">
    box full(w-full h-full)
  </div>

 # 抽取的弊端, hover 上去没有提示!!
  <div className=" container-full bg-slate-400">
    box full(container-full)
  </div>
  
# tailwind.css file
@layer components {
  .container-full {
    @apply w-full h-full; # 意思就是将 w-full h-full 应用于 container-full 类名上
  }
}

你可能会遇到的问题

  • 动态类名问题,其实就是没有遵循原子化的思想,或者说是破坏了原子化、动态拼接的类名会导致 tailwind 解析器使用正则匹配失效,解决方案就是保证原子类名的完整性
  • 类名的优先级问题 方案是 使用 tailwind-mergeclassnamesclsx 来解决