Tailwind CSS 使用指南

0x01 概述

(1)简介

  • Tailwind CSS 官网:https://www.tailwindcss.cn/
  • Tailwind CSS 是一个 CSS 框架,使用初级“工具”类创建布局
  • 如 Bootstrap 等传统 CSS 框架,其使用的类通常与组件直接相关;然而,Tailwind 则采用了不同的方法,它将类作为工具集合,让用户能够自由组合这些工具来构建个性化的自定义组件
  • 工具类是简单的 HTML 类,其作用域通常为单个和特定 CSS 属性,具有以下优势
    • 根据目的命名
    • 易于理解和记忆
    • 作用浅显易懂
    • 不存在命名不一致
    • 支持快速布局创建和测试
  • Tailwind 有一个条件类,用于为断点、响应状态等命名

(2)基本环境配置

  • 代码文本编辑工具:VSCode 或其他
    • 推荐插件:
      • 标签重命名:Auto Rename Tag
      • 实时加载:Live Server
      • PostCSS 语法支持:PostCSS Language Support
      • 代码格式化:Prettier
      • Tailwind 官方补全:Tailwind CSS IntelliSense
  • 包管理器:Node.js 或其他
  • (可选)版本控制:Git

(3)创建项目

  1. 在任意位置新建一个 index.html
  2. 使用 CDN 引入 Tailwind:https://cdn.tailwindcss.com/
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdn.tailwindcss.com/"></script>
  </head>
  <body></body>
</html>

0x02 基本原理

(1)使用颜色

  • 默认包含的颜色:

    black white red green blue orange
    yellow purple lime emerald teal cyan
    indigo violet fuchsia pink rose sky
    gray slate zinc neutral stone amber
  • 文本颜色:text-[color]-[shade]

    • color:颜色名称
    • shade:色度,取值范围为 100~900,不可对黑色或白色使用
    <p class="text-black">Color Black</p>
    <p class="text-white">Color White</p>
    <p class="text-red-500">Color Red 500</p>
    <p class="text-blue-500">Color Blue 500</p>
    <p class="text-gray-500">Color Gray 500</p>
    <p class="text-green-500">Color Green 500</p>
    
  • 背景颜色:bg-[color]-[shade]

    <p class="bg-white">BgColor White</p>
    <p class="bg-red-500">BgColor Red 500</p>
    <p class="bg-black text-white">BgColor Black</p>
    
  • 下划线颜色:underline decoration-[color]-[shade]

    • underline:添加下划线
    <p class="underline">UlColor Default</p>
    <p class="underline decoration-red-500">UlColor Red 500</p>
    <p class="underline decoration-green-500">UlColor Green 500</p>
    
  • 边框颜色:border border-[color]-[shade]

    • border:添加边框
    <input type="text" class="border" />
    <input type="text" class="border border-red-500" />
    <input type="text" class="border border-green-500" />
    
  • 间隔颜色:divide-[direct] divide-[color]-[shade]

    • divide-[direct]:添加分隔,direct 表示分隔方向,取值 x-横向、y-纵向
    <div class="divide-y divide-red-500">
      <div>Item 1</div>
      <div>Item 2</div>
      <div>Item 3</div>
    </div>
    
  • 轮廓线颜色:outline outline-[color]-[shade]

    • outline:添加轮廓线
    <button class="outline">OlColor Default</button>
    <button class="outline outline-red-500">OlColor Red 500</button>
    <button class="outline outline-green-500">OlColor Green 500</button>
    
  • 盒子阴影颜色:shadow-[container] shadow-[color]-[shade(/opacity)]

    • shadow-[container]:添加阴影,container 表示阴影最大宽度,取值如下

      container width
      sm 640px
      md 768px
      lg 1024px
      xl 1280px
      2xl 1536px
    • (/opacity):透明度,默认 100,取值 0~100

    <div class="shadow-lg">SdColor Red 500</div>
    <div class="shadow-lg shadow-red-500">SdColor Red 500</div>
    <div class="shadow-lg shadow-red-500/20">SdColor Red 500</div>
    
  • 强调颜色:accent-[color]-[shade]

    <input type="checkbox" checked />
    <input type="checkbox" class="accent-red-500" checked />
    <input type="checkbox" class="accent-green-500" checked />
    
  • 自定义颜色:-[(#xxxxx|rgb(r,g,b)|name)]

    • 十六进制、RGB、名称
    <p class="text-[#4682B4]">Color #4682B4</p>
    <p class="text-[rgb(46,130,180)]">Color RGB(46,130,180)</p>
    <p class="text-[steelblue]">Color Steelblue</p>
    

(2)容器与间距

  • 容器

    <div class="container mx-auto">
      <article>
        <h3>Title</h3>
        <p>Tailwind CSS is the only framework that I've
          seen scale on large teams. It’s easy to customize,
          adapts to any design, and the build size is tiny.</p>
      </article>
    </div>
    
    • container:标记为容器
    • mx-auto:x 轴方向(横向)上,外边距(margin)自动
  • 外边距:m?-[number]

    • m?m-Margin、mt-MarginTop、ml-MarginLeft、mr-MarginRight、mb-MarginBottom
    • number=number * 0.25rem=number * 4px
      • 如:m-2 意思为 margin: 0.5rem
    <div class="bg-red-200 m-2">Margin 2</div>
    <div class="bg-red-200 ml-2">Margin Left 2</div>
    <div class="bg-red-200 mr-2">Margin Right 2</div>
    <div class="bg-red-200 mt-2">Margin Top 2</div>
    <div class="bg-red-200 mb-2">Margin Bottom 2</div>
    <div class="bg-red-200 m-[20px]">Margin 20px</div>
    
  • 内边距:p?-[number]

    • p?p-Padding、pt-PaddingTop、pl-PaddingLeft、pr-PaddingRight、pb-PaddingBottom
    • number=number * 0.25rem=number * 4px
    <div class="bg-red-200 mb-1 p-2">Padding 2</div>
    <div class="bg-red-200 mb-1 pl-2">Padding Left 2</div>
    <div class="bg-red-200 mb-1 pr-2">Padding Right 2</div>
    <div class="bg-red-200 mb-1 pt-2">Padding Top 2</div>
    <div class="bg-red-200 mb-1 pb-2">Padding Bottom 2</div>
    <div class="bg-red-200 mb-1 p-[20px]">Padding 20px</div>
    
  • 间距:(-)space-[direct]-[number]

    • (-):负间距
    • direct:间隔方向,取值 x-横向、y-纵向
    • number=number * 0.25rem=number * 4px
    <div class="flex space-x-2">
      <div>Item 1</div>
      <div>Item 2</div>
      <div>Item 3</div>
    </div>
    <div class="flex flex-col space-x-2">
      <div>Item 1</div>
      <div>Item 2</div>
      <div>Item 3</div>
    </div>
    
    • flex:采用 Flex 布局
    • flex-col:Flex 布局纵向

(3)版面设计

  • 字体:font-[family]

    <div class="font-sans">Font Sans</div>
    <div class="font-serif">Font Serif</div>
    <div class="font-mono">Font Mono</div>
    
    • 自定义字体族配置

      <head>
        <!-- ... -->>
        <script>
          tailwind.config = {
            theme: {
              fontFamily: {
                sans: ["Inter", "sans-serif"],
                serif: ["Inter", "serif"],
                mono: ["Inter", "monospace"]
              }
            }
          }
        </script>
      </head>
      
  • 字号:text-[size]

    <div class="text-xs">Text Extra Small</div>
    <div class="text-sm">Text Small</div>
    <div class="text-base">Text Base</div>
    <div class="text-lg">Text Large</div>
    <div class="text-xl">Text Extra Large</div>
    <div class="text-2xl">Text 2 Extra Large</div>
    <div class="text-3xl">Text 3 Extra Large</div>
    
  • 字重:font-[weight]

    <div class="font-light">Font Light</div>
    <div class="font-normal">Font Normal</div>
    <div class="font-medium">Font Medium</div>
    <div class="font-semibold">Font Semibold</div>
    <div class="font-bold">Font Bold</div>
    
  • 字距:tracking-[space]

    <div class="tracking-tight">Tracking Tight</div>
    <div class="tracking-normal">Tracking Normal</div>
    <div class="tracking-wide">Tracking Wide</div>
    
  • 文本对齐:text-[direct]

    <div class="text-left">Text Left</div>
    <div class="text-center">Text Center</div>
    <div class="text-right">Text Right</div>
    
  • 下划线重:decoration-[weight]

    <div class="underline decoration-2">Decoration 2</div>
    <div class="underline decoration-4">Decoration 4</div>
    <div class="underline decoration-8">Decoration 8</div>
    
  • 下划线风格:decoration-[type]

    <div class="underline decoration-double">Decoration Double</div>
    <div class="underline decoration-dotted">Decoration Dotted</div>
    <div class="underline decoration-dashed">Decoration Dashed</div>
    <div class="underline decoration-wavy">Decoration Wavy</div>
    
  • 装饰偏移量:underline-offset-[number]

    <div class="underline underline-offset-2">Offset 2</div>
    <div class="underline underline-offset-4">Offset 4</div>
    <div class="underline underline-offset-8">Offset 8</div>
    
  • 文本变换:

    <p class="normal-case">Normal Case</p>
    <p class="uppercase">uppercase</p>
    <p class="lowercase">LOWERCASE</p>
    <p class="capitalize">capitalize test</p>
    

(4)宽度与高度

  • 宽度:w-[number]

    • number 取值 0~48
    <div class="bg-black text-white mb-2 w-6">Width 1.5rem</div>
    <div class="bg-black text-white mb-2 w-12">Width 3rem</div>
    <div class="bg-black text-white mb-2 w-24">Width 6rem</div>
    
  • 百分比:w-[number_1]/[number_2]

    <div class="bg-black text-white mb-2 w-1/4">Width 25%</div>
    <div class="bg-black text-white mb-2 w-1/3">Width 33%</div>
    <div class="bg-black text-white mb-2 w-1/2">Width 50%</div>
    
  • 视点宽度

    <div class="bg-black text-white w-screen">Width 100vw</div>
    
  • 100% 容器

    <div class="bg-black text-white w-full">Width 100%</div>
    
  • 自定义宽度

    <div class="bg-black text-white w-[300px]">Width 300px</div>
    
  • 最大宽度:max-w-[size]

    <div class="bg-black text-white mx-auto max-w-xs">
      Tailwind CSS is the only framework that I've
      seen scale on large teams. It’s easy to customize,
      adapts to any design, and the build size is tiny.
    </div>
    
  • 高度(大部分与宽度方法相同):h-[number]

    • number 取值 0~96
    <div class="flex items-end">
      <div class="bg-black text-white w-20 h-24">Height 24</div>
      <div class="bg-black text-white w-20 h-48">Height 48</div>
      <div class="bg-black text-white w-20 h-72">Height 72</div>
      <div class="bg-black text-white w-20 h-96">Height 96</div>
    </div>
    
  • 全屏高度

    <div class="bg-black text-white h-screen">Height 100vh</div>
    

(5)布局与定位

  • 定位:相对定位与绝对定位

    <div class="relative w-1/2 h-12 bg-red-200">
      <p>Parent</p>
      <div class="absolute bottom-0 right-0 bg-red-700">
        <p>Child</p>
      </div>
    </div>
    
  • 左上角

    <div class="relative w-32 h-32 bg-red-200">
      <div class="absolute w-16 h-16 top-0 left-0 bg-red-700"></div>
    </div>
    
  • 右上角

    <div class="relative w-32 h-32 bg-red-200">
      <div class="absolute w-16 h-16 top-0 right-0 bg-red-700"></div>
    </div>
    
  • 左下角

    <div class="relative w-32 h-32 bg-red-200">
      <div class="absolute w-16 h-16 bottom-0 left-0 bg-red-700"></div>
    </div>
    
  • 右下角

    <div class="relative w-32 h-32 bg-red-200">
      <div class="absolute w-16 h-16 bottom-0 right-0 bg-red-700"></div>
    </div>
    
  • 顶边

    <div class="relative w-32 h-32 bg-red-200">
      <div class="absolute h-16 top-0 inset-x-0 bg-red-700"></div>
    </div>
    
  • 左边

    <div class="relative w-32 h-32 bg-red-200">
      <div class="absolute w-16 left-0 inset-y-0 bg-red-700"></div>
    </div>
    
  • 右边

    <div class="relative w-32 h-32 bg-red-200">
      <div class="absolute w-16 right-0 inset-y-0 bg-red-700"></div>
    </div>
    
  • 底边

    <div class="relative w-32 h-32 bg-red-200">
      <div class="absolute h-16 bottom-0 inset-x-0 bg-red-700"></div>
    </div>
    
  • 显示方式

    <div>
      Tailwind CSS is the only framework that 
      <span class="text-red-500 inline">(Inline)</span>
      I've seen scale on large teams.
      <span class="text-red-500 inline-block">(Inline-block)</span>
      It’s easy to customize, adapts to any design,
      <span class="text-red-500 block">(Block)</span>
      and the build size is tiny.
      <span class="text-red-500 hidden">(Hidden)</span>
    </div>
    
  • 层叠等级(Z 轴索引):z-[number/auto]

    <div class="relative h-24">
      <div class="absolute left-0 w-24 h-24 bg-red-100 z-40">1</div>
      <div class="absolute left-20 w-24 h-24 bg-red-200 z-30">2</div>
      <div class="absolute left-40 w-24 h-24 bg-red-500 z-20">3</div>
      <div class="absolute left-60 w-24 h-24 bg-red-700 z-10">4</div>
      <div class="absolute left-80 w-24 h-24 bg-red-900">5</div>
    </div>
    
  • 浮动:float-[left/right/none]

    <div class="h-24">
      <div class="w-24 h-24 bg-red-100 float-left">1</div>
      <div class="w-24 h-24 bg-red-200 inline-block">2</div>
    </div>
    

(6)背景与阴影

  • 背景

    <div
      class="w-64 h-64 bg-cover bg-no-repeat bg-center"
      style="background-image: url('https://example.com/png');"
    ></div>
    
    • 大小

      bg-auto bg-cover bg-contain
    • 重复

      bg-repeat bg-no-repeat bg-repeat-x
      bg-repeat-y bg-repeat-round bg-repeat-space
    • 定位

      bg-center bg-top bg-bottom
      bg-left bg-left-top bg-left-bottom
      bg-right bg-right-top bg-right-bottom
    • attachment

      bg-fixed bg-local bg-scroll
  • 渐变:bg-gradient-to-[direct] from-[color]-[shade] to-[color]-[shade]

    <div class="h-24 bg-gradient-to-r from-red-500 to-blue-500"></div>
    
  • 阴影

    <div class="w-96 shadow-2xl">
      Consectetur velit laboris tempor laboris qui consequat eu minim ipsum nulla culpa aliquip ad.
    </div>
    
    Tailwind Background Class CSS Code
    shadow-sm box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05);
    shadow box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1),
    0 1px 2px -1px rgb(0 0 0 / 0.1);
    shadow-md box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1),
    0 2px 4px -2px rgb(0 0 0 / 0.1);
    shadow-lg box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1),
    0 4px 6px -4px rgb(0 0 0 / 0.1);
    shadow-xl box-shadow: 0 20px 25px -5px rgb(0 0 0 / 0.1)
    0 8px 10px -6px rgb(0 0 0 / 0.1);
    shadow-2xl box-shadow: 0 25px 50px -12px rgb(0 0 0 / 0.25);
    shadow-inner box-shadow: inset 0 2px 4px 0 rgb(0 0 0 / 0.05);
    shadow-none box-shadow: 0 0 #0000;
  • 混合

    <div class="flex justify-center -space-x-24">
      <div class="mix-blend-multiply bg-red-500">
        Id ex deserunt velit excepteur deserunt tempor eu aliquip ipsum labore laboris.
      </div>
      <div class="mix-blend-multiply bg-blue-500">
        Adipisicing voluptate magna aute sunt consequat irure sint.
      </div>
    </div>
    

(7)边框

  • 宽度:border(-[direct])-[width]

    • (-[direct]):取值为 t、l、r、b、x 或 y,分别对应上、左、右、下、左右或上下
    • width:取值为 0、2、4 或 8,分别对应 0px、2px、4px、8px
    <div class="w-96 m-5 p-5 border-2">
      Amet commodo nisi quis irure velit Lorem enim anim commodo sunt aliquip officia quis.
    </div>
    <div class="w-96 m-5 p-5 border-x-4">
      Amet commodo nisi quis irure velit Lorem enim anim commodo sunt aliquip officia quis.
    </div>
    <div class="w-96 m-5 p-5 border-y-8">
      Amet commodo nisi quis irure velit Lorem enim anim commodo sunt aliquip officia quis.
    </div>
    
  • 颜色

    详见本章第(1)小节“边框颜色”部分

  • 圆角:rounded(-[direct])(-[size])

    • (-[direct]):取值为 t、l、r、b、x 或 y,分别对应上、左、右、下、左右或上下
    • (-[size]):取值为 none、sm、【略】、md、lg、xl、2xl、3xl、full
    <div class="w-96 w-5 p-5 border-4 rounded-xl">
      Dolore deserunt sunt qui ut quis sunt anim do nostrud minim fugiat minim.
    </div>
    
  • 轮廓线:outline(-[width])

    • (-[width]):取值为 0、1、2、4、8
    <button class="m-5 outline outline-8">Click</button>
    

(8)过滤器

  • 模糊:blur(-[size])

    • (-[size]):取值为 none、sm、【略】、md、lg、xl、2xl、3xl
    <div class="blur-sm">
      Do elit adipisicing cupidatat dolor excepteur nulla in incididunt.
    </div>
    
  • 亮度:brightness-[number]

    • numberfilter: brightness(number*0.1)
    <div class="h-16 bg-red-500 brightness-0">Brightness 0</div>
    <div class="h-16 bg-red-500 brightness-100">Brightness 100</div>
    <div class="h-16 bg-red-500 brightness-200">Brightness 200</div>
    
  • 对比度:contrast-[number]

    • numberfilter: contrast(number*0.1)
    <div class="h-16 bg-red-500 contrast-0">Contrast 0</div>
    <div class="h-16 bg-red-500 contrast-50">Contrast 50</div>
    <div class="h-16 bg-red-500 contrast-200">Contrast 200</div>
    
  • 灰度

    <div class="h-16 bg-red-500 grayscale">Grayscale</div>
    
  • 反色

    <div class="h-16 bg-red-500 invert">Invert</div>
    
  • 褐化

    <div class="h-16 bg-red-500 sepia">Sepia</div>
    
  • Hue rotate:hue-rotateo-[number]

    • number:取值为 0、15、30、60、90、180
    <div class="h-16 bg-red-500 hue-rotate-0">Hue Rotate 0</div>
    <div class="h-16 bg-red-500 hue-rotate-90">Hue Rotate 90</div>
    <div class="h-16 bg-red-500 hue-rotate-180">Hue Rotate 180</div>
    

0x03 进阶应用

(1)交互

  • 悬停:hover:

    <button class="bg-black text-white rounded-lg m-5 p-5 hover:bg-blue-200 hover:text-black">Click</button>
    
  • 聚焦:focus:

    <button class="bg-black text-white rounded-lg m-5 p-5 focus:bg-blue-200 focus:text-black">Click</button>
    
  • 触发:active:

    <button class="bg-black text-white rounded-lg m-5 p-5 active:bg-blue-200 active:text-black">Click</button>
    
  • 设置内部元素样式

    <div class="group block max-w-xs mx-auto rounded-lg p-6 bg-white shadow-lg space-y-3 hover:bg-red-500">
      <h3 class="hover:text-white">Title</h3>
      <p class="group-hover:text-white">Laboris tempor ex nisi deserunt labore anim et do in officia sint laborum.</p>
    </div>
    
  • 伪类

    <ul>
      <li class="first:bg-red-500">Item 1</li>
      <li class="first:bg-red-500">Item 2</li>
      <li class="first:bg-red-500 even:bg-red-200 odd:bg-red-700">Item 3</li>
      <li class="first:bg-red-500 even:bg-red-200 odd:bg-red-700">Item 4</li>
      <li class="first:bg-red-500 even:bg-red-200 odd:bg-red-700">Item 5</li>
    </ul>
    
  • 外观

    • 一般用于重置浏览器或操作系统默认的样式外观
    <select class="border-4 border-red-500">
      <option value="1">True</option>
      <option value="0">False</option>
    </select>
    <select class="border-4 border-green-500 appearance-none">
      <option value="1">True</option>
      <option value="0">False</option>
    </select>
    
  • 游标:cursor-[type]

    • type 常见取值为

      auto default pointer wait text move help
      not-allowed none context-menu progress cell crosshair vertical-text
      ...
    <div class="w-36 h-36 bg-red-500 cursor-pointer"></div>
    
  • 选中

    <div class="select-none">Select None</div>
    <div class="select-text">Select Text</div>
    <div class="select-all">Select All</div>
    <div class="select-auto">Select Auto</div>
    
  • 平滑滚动示例

    <!DOCTYPE html>
    <html lang="en" class="scroll-smooth">
      <head>
        <!-- ... -->
        <script src="https://cdn.tailwindcss.com/"></script>
      </head>
      <body>
        <a href="#bottom" class="block m-6 border-4 text-center">Go to Bottom</a>
        <div class="h-[1000px] bg-black"></div>
        <div id="bottom" class="h-4 text-center">Bottom</div>
      </body>
    </html>
    

(2)断点类与媒体查询

  1. 窗口宽度实时监听

    <body>
      <h1></h1>
      <script>
        function showBrowserWidth() {
          const width = window.innerWidth
          document.querySelector('h1').innerText = `Width: ${width}`
        }
        window.onload = showBrowserWidth
        window.onresize = showBrowserWidth
      </script>
    </body>
    
  2. 修改 h1 标签样式,设置默认背景颜色

    <body class="bg-black">
      <h1 class="text-white text-4xl"></h1>
      <script>
        function showBrowserWidth() {
          const width = window.innerWidth
          document.querySelector('h1').innerText = `Width: ${width}`
        }
        window.onload = showBrowserWidth
        window.onresize = showBrowserWidth
      </script>
    </body>
    
  3. body 标签中,根据窗口宽度设置背景颜色变化

    <body class="bg-black sm:bg-red-700">
      <!-- ... -->
    </body>
    
    size min-width
    sm 640px
    md 768px
    lg 1024px
    xl 1280px
    2xl 1536px

(3)分栏

  • 基本列:columns-[number/type]

    • number:取值 1~12
    • type:取值 auto、3xs、2xs、xs、sm、md、lg、xl、2xl、3xl、4xl、5xl、6xl、7xl
    <div class="columns-3">
      <div class="w-full m-2 border-4 border-red-500">Proident ipsum consequat dolor deserunt.</div>
      <div class="w-full m-2 border-4 border-yellow-500">Proident ipsum consequat dolor deserunt.</div>
      <div class="w-full m-2 border-4 border-green-500">Proident ipsum consequat dolor deserunt.</div>
      <div class="w-full m-2 border-4 border-blue-500">Proident ipsum consequat dolor deserunt.</div>
    </div>
    
  • 纵横比:aspect-[type]

    <div class="columns-1">
      <div class="w-60 m-2 border-4 border-red-500 aspect-square">Proident ipsum consequat dolor deserunt.</div>
      <div class="w-60 m-2 border-4 border-blue-500 aspect-video">Proident ipsum consequat dolor deserunt.</div>
    </div>
    

(4)Flexbox

  • Flex 与对齐

    1. 创建一个 Flexbox

      <div class="flex w-full h-72 bg-black">
        <div class="p-10 border border-red-500 bg-red-200">1</div>
        <div class="p-10 border border-yellow-500 bg-yellow-200">2</div>
        <div class="p-10 border border-green-500 bg-green-200">3</div>
        <div class="p-10 border border-blue-500 bg-blue-200">4</div>
      </div>
      
    2. 设置每项的对齐方向:items-[type]

      <div class="flex w-full h-72 bg-black items-center">
        <!-- ... -->
      </div>
      
    3. 设置每项的对齐方式:justify-[type]

      <div class="flex w-full h-72 bg-black items-center justify-around">
        <!-- ... -->
      </div>
      
    4. 设置换行,使某一项超出窗口:flex-wrap

      <div class="flex flex-wrap w-full h-72 bg-black items-center justify-around">
        <div class="p-10 border border-red-500 bg-red-200">1</div>
        <div class="p-10 border border-yellow-500 bg-yellow-200">2</div>
        <div class="p-10 w-[300px] border border-green-500 bg-green-200">3</div>
        <div class="p-10 border border-blue-500 bg-blue-200">4</div>
      </div>
      
  • 列、间隙、顺序

    1. 创建一个 Flexbox,设置为纵向排列

      <div class="flex flex-col w-72 bg-black">
        <div class="p-10 border border-red-500 bg-red-200">1</div>
        <div class="p-10 border border-yellow-500 bg-yellow-200">2</div>
        <div class="p-10 border border-green-500 bg-green-200">3</div>
        <div class="p-10 border border-blue-500 bg-blue-200">4</div>
      </div>
      
    2. 设置间隙:gap-[number]number * 0.25rem)

      <div class="flex flex-col w-72 bg-black gap-4">
        <!-- ... -->
      </div>
      
    3. 调整顺序:order-[index]

      <div class="flex flex-col w-72 bg-black gap-4">
        <div class="p-10 border border-red-500 bg-red-200 order-2">1</div>
        <div class="p-10 border border-yellow-500 bg-yellow-200 order-1">2</div>
        <div class="p-10 border border-green-500 bg-green-200 order-4">3</div>
        <div class="p-10 border border-blue-500 bg-blue-200 order-3">4</div>
      </div>
      
  • 放大与缩小

    <div class="flex w-full bg-black">
      <div class="p-10 w-64 border border-red-500 bg-red-200">1</div>
      <div class="flex-none p-10 w-64 border border-yellow-500 bg-yellow-200">2</div>
      <div class="p-10 w-64 border border-green-500 bg-green-200">3</div>
      <div class="p-10 border border-blue-500 bg-blue-200">4</div>
      <div class="p-10 w-64 border border-gray-500 bg-gray-200">5</div>
    </div>
    

(5)Grid

  • 模板列:grid-cols-[number/none]

    • number:取值为 1~12
    • 该语句等同于:grid-template-columns: repeat(number, minmax(0, 1fr));
    <div class="grid grid-cols-3 gap-2">
      <div class="p-10 border-4 border-red-200 bg-blue-200">Item 1</div>
      <div class="p-10 border-4 border-red-200 bg-blue-200">Item 2</div>
      <div class="p-10 border-4 border-red-200 bg-blue-200">Item 3</div>
      <div class="p-10 border-4 border-red-200 bg-blue-200">Item 4</div>
      <div class="p-10 border-4 border-red-200 bg-blue-200">Item 5</div>
      <div class="p-10 border-4 border-red-200 bg-blue-200">Item 6</div>
      <div class="p-10 border-4 border-red-200 bg-blue-200">Item 7</div>
      <div class="p-10 border-4 border-red-200 bg-blue-200">Item 8</div>
      <div class="p-10 border-4 border-red-200 bg-blue-200">Item 9</div>
    </div>
    
  • 模板行:grid-rows-[number/none]

    • number:取值为 1~6
    • 该语句等同于:grid-template-rows: repeat(number, minmax(0, 1fr));
    <div class="grid grid-cols-2 gap-2 grid-rows-4 bg-gray-200">
      <!-- ... -->
    </div>
    
  • 跨行/列:[row/col]-span-[number]

    • row-span-[number]:跨 number
    • col-span-[number]:跨 number
    <div class="grid grid-cols-3 gap-2">
      <div class="row-span-3 p-10 border-4 border-red-200 bg-blue-200">Item 1</div>
      <div class="md:col-span-2 p-10 border-4 border-red-200 bg-blue-200">Item 2</div>
      <!-- ... -->
    </div>
    

(6)过渡与变换

初始按钮:

<button class="m-4 px-8 py-4 text-white bg-blue-200 rounded hover:bg-blue-700">Click</button>
  • 过渡

    • transition-[type]:过渡类型,type 取值为 none、all、colors、opacity、shadow、transform
    • duration-[ms]:过渡时长,ms 取值为 75、100、150、200、300、500、700、1000
    • ease-[type]:过渡效果,type 取值为 linear、in、out、in-out
    • delay-[ms]:延时时长,ms 取值为 75、100、150、200、300、500、700、1000
    <button class="m-4 px-8 py-4 text-white bg-blue-200 rounded hover:bg-blue-700 transition-colors duration-700 ease-in delay-100">Click</button>
    
  • 变换

    • scale(-[axis])-[magnification]:缩放,axis 表示参照轴,取值为 x 或 y;magnification 表示缩放倍率,为 number%
    • rotate-[degree]:旋转,degree 表示旋转角度
    • translate-[axis]-[distance]:位移,axis 表示参照轴,取值为 x 或 y;distance 表示位移距离,整数为 number * 0.25rem,分数为占比,full 为 100%,px 为 1px
    • skew-[direct]-[degree]:倾斜,axis 表示参照轴,取值为 x 或 y;degree 表示倾斜角度
    <button class="m-4 px-8 py-4 text-white bg-blue-200 rounded hover:scale-50 hover:rotate-12 hover:translate-x-2 hover:skew-x-12 duration-700">Click</button>
    

(7)动画类与关键帧

  • animate-[property]property 取值如下:

    • none:animation: none;

    • spin:旋转

      animate: spin 1s linear infinite;
      @keyframes spin {
          from {
              transform: rotate(0deg);
          }
          to {
              transform: rotate(360deg);
          }
      }
      
    • ping:扩散

      animation: ping 1s cubic-bezier(0, 0, 0.2, 1) infinite;
      @keyframes ping {
          75%, 100% {
              transform: scale(2);
              opacity: 0;
          }
      }
      
    • pulse:闪烁

      animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
      @keyframes pulse {
          0%, 100% {
              opacity: 1;
          }
          50% {
              opacity: .5;
          }
      }
      
    • bounce:弹跳

      animation: bounce 1s infinite;
      @keyframes bounce {
          0%, 100% {
              transform: translateY(-25%);
              animation-timing-function: cubic-bezier(0.8, 0, 1, 1);
          }
          50% {
              transform: translateY(0);
              animation-timing-function: cubic-bezier(0, 0, 0.2, 1);
          }
      }
      
    <div class="w-64 h-64 bg-red-200 rounded-full relative animate-ping">
      <div class="w-32 h-2 bg-gradient-to-r from-red-500 to-yellow-500 absolute right-0 top-1/2"></div>
    </div>
    
  • 自定义动画与关键帧

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <!-- ... -->
        <script>
          tailwind.config = {
            theme: {
              extend: {
                animation: {
                  'slow-spin': 'spin 3s linear infinite',
                  'custom': 'custom 1s linear infinite'
                },
                keyframes: {
                  'custom': {
                    '0%': {
                      transform: 'rotate(0deg)'
                    },
                    '90%, 100%': {
                      transform: 'rotate(360deg)'
                    }
                  }
                }
              }
            }
          }
        </script>
      </head>
      <body>
        <div class="w-64 h-64 bg-red-200 rounded-full relative animate-custom">
          <div class="w-32 h-2 bg-gradient-to-r from-red-500 to-yellow-500 absolute right-0 top-1/2"></div>
        </div>
      </body>
    </html>
    

(8)配置与客制化

  • head 标签中的 script 标签中写入配置

  • 配置格式:

    <script>
      tailwind.config = {
        theme: {
          extend: {
            'property-1': {
              'key-1-1': 'value-1-1',
            },
            'property-2': {
              'key-2-1': 'value-2-1',
            },
            // ...
          }
        }
      }
    </script>
    

(9)夜间模式

  • 配置夜间模式样式:dark:

    <div class="w-64 h-64 bg-white dark:bg-gray-900"></div>
    
  • 是否使用夜间模式,默认根据操作系统

  • 使用 Javascript 控制夜间模式

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <!-- ... -->
        <script>
          tailwind.config = {
            darkMode: "class",
          };
        </script>
        <style>
          .toggle-checkbox:checked {
            right: 0;
            border-color: #68d391;
          }
          .toggle-checkbox:checked + .toggle-label {
            background: #68d391;
          }
        </style>
      </head>
      <body>
        <div
          class="container mx-auto mt-10 bg-white dark:bg-slate-900 rounded-xl px-6 py-8 shadow-xl"
        >
          <h3 class="text-slate-900 dark:text-white font-medium tracking-tight">
            Title
          </h3>
          <p class="text-slate-500 dark:text-slate-400 mt-2 text-sm">
            Irure dolor ut excepteur ea cupidatat dolor dolore consectetur sit
            voluptate qui et deserunt.
          </p>
        </div>
        <div
          class="relative inline-block w-10 mr-2 mt-6 ml-6 align-middle select-none transition duration-200 ease-in"
        >
          <input
            type="checkbox"
            name="toggle"
            id="toggle"
            class="toggle-checkbox absolute block w-6 h-6 rounded-full bg-white border-4 dark:bg-gray-700 appearance-none cursor-pointer"
          />
          <label
            for="toggle"
            class="toggle-label block overflow-hidden h-6 rounded-full bg-gray-300 cursor-pointer"
          ></label>
        </div>
        <script>
          document.getElementById("toggle").addEventListener("change", function () {
            if (this.checked) {
              document.documentElement.classList.add("dark");
            } else {
              document.documentElement.classList.remove("dark");
            }
          });
        </script>
      </body>
    </html>
    

0x04 更好的开发环境

(1)基于 Tailwind CLI 构建环境

之前使用 CDN 的方式使用 Tailwind 并非生产的最佳选择,Tailwind 还支持使用 Tailwind CLI 等方式

  1. 创建一个目录作为 Tailwind 项目的根目录

  2. 在该目录下,使用命令 npm init -y 创建一个 package.json 作为包管理

  3. 使用命令 npm install -D tailwindcss 引入 Tailwind

  4. 使用命令 npx tailwindcss init 创建用于初始化 Tailwind 的配置文件—— tailwind.config.js

  5. 修改 tailwind.config.js,允许 Tailwind 控制当前目录下所有后缀为 html 的文件

    /** @type {import('tailwindcss').Config} */
    module.exports = {
      content: ['./*.html'],
      theme: {
        extend: {},
      },
      plugins: [],
    }
    
  6. 创建 input.css 作为主 CSS 文件

    @tailwind base;
    @tailwind components;
    @tailwind utilities;
    
  7. 修改 package.json,配置指令实现开启 Tailwind CLI 构建流程

    {
      // ...
      "scripts": {
        "build": "tailwindcss -i ./input.css -o ./css/style.css",
        "watch": "tailwindcss -i ./input.css -o ./css/style.css --watch",
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      // ...
    }
    
  8. 使用命令 npm run build 构建 CSS 文件及其目录

  9. 创建 index.html,其中引入生成的 style.css,并添加一个标签使用 Tailwind

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <link rel="stylesheet" href="css/style.css" />
        <title>Document</title>
      </head>
      <body>
        <h1 class="text-3xl text-red-500">Tailwind CSS</h1>
      </body>
    </html>
    
  10. 使用命令 npm run watch 实时使用 Tailwind 渲染页面

(2)指令与函数

a. 指令

指令是 Tailwind 特定于可以在CSS中使用的规则,这些规则为 Tailwind 项目提供特殊的功能

  • @tailwind:用于插入 Tailwind 的基本(base)、组件(components)以及工具类(utilities)等

  • @apply:用于获取工具类中的样式

    h1 {
        @apply text-xl;
    }
    
  • @layer:用于创建自定义样式

    @layer base {
        h1 {
            font-size: 2rem;
        }
    }
    @layer components {
        btn-blue {
            @apply bg-blue-500 px-4 py-2 rounded-xl font-bold hover:bg-blue-700;
        }
    }
    
  • @config:用于指定 Tailwind 在编译该 CSS 文件时应使用的配置文件

    @config "./tailwind.input.config.js";
    

b. 函数

函数用于访问 Tailwind 中的特定值,构建后会使用静态值替换

  • theme():可以使用点表示法访问 Tailwind 配置值

    1. 修改 tailwind.config.js

      /** @type {import('tailwindcss').Config} */
      module.exports = {
        content: ['./*.html'],
        theme: {
          extend: {
            spacing: {
              128: '32rem'
            }
          },
        },
        plugins: [],
      }
      
    2. 修改 input.css,引入 spacing-128

      .content {
        height: theme('spacing.128');
      }
      
  • screen():可以创建按名称引用断点的媒体查询

    @media screen(xl) {
        body {
            @apply bg-black text-white;
        }
    }
    

(3)使用 Webpack 与 PostCSS 环境

  • Webpack 是一个模块打包工具,可以将带有依赖的模块打包成静态资源,官网链接
  • PostCSS 是一个用 JavaScript 工具和插件转换 CSS 代码的工具,官网链接
  1. 创建一个目录作为 Tailwind 项目的根目录

  2. 在该目录下,使用命令 npm init -y 创建一个 package.json 作为包管理

  3. 使用命令 npm install -D webpack webpack-cli webpack-dev-server style-loader css-loader postcss postcss-loader posscss-preset-env 安装 Webpack 与 PostCSS 以及相关加载器

  4. 在根目录创建 src 目录,其中新建 index.js,作为 Webpack 的入口文件

  5. 在根目录创建 webpack.config.js 文件,用于配置 Webpack

    const path = require('path')
    
    module.exports = {
      mode: 'development',
      entry: './src/index.js',
      output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js',
      },
    }
    
  6. 修改 package.json,配置指令实现开启 Webpack 构建流程

    {
      // ...
      "scripts": {
        "build": "webpack"
      },
      // ...
    }
    
  7. 使用命令 npm run build 构建主 Javascript 文件及其目录 dist

  8. 在 dist 目录下,创建 index.html,其中引入生成的 bundle.js

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>Document</title>
        <script src="bundle.js"></script>
      </head>
      <body>
        <h1 class="text-3xl text-red-500">Tailwind CSS</h1>
      </body>
    </html>
    
  9. 修改 webpack.config.js,设置 Webpack 开发服务器,用于实时使用渲染页面

    const path = require('path')
    
    module.exports = {
      // ...
      devServer: {
        static: {
          directory: path.resolve(__dirname, 'dist'),
        },
        port: 9000,
        open: true,
        hot: true,
        compress: true,
        historyApiFallback: true,
      },
    }
    
  10. 修改 package.json,配置指令实现开启 Webpack 构建流程

    {
      // ...
      "scripts": {
        "build": "webpack",
        "dev": "webpack serve"
      },
      // ...
    }
    
  11. 使用命令 npm run dev 开启 Webpack 开发服务器

  12. 修改 webpack.config.js,设置样式加载器

    const path = require('path')
    
    module.exports = {
      // ...
      module: {
        rules: [
          {
            test: /\.css$/i,
            include: path.resolve(__dirname, 'src'),
            use: ['style-loader', 'css-loader', 'postcss-loader'],
          },
        ],
      },
    }
    
  13. 使用命令 npm install -D tailwindcss 引入 Tailwind

  14. 使用命令 npx tailwindcss init 创建用于初始化 Tailwind 的配置文件—— tailwind.config.js

  15. 修改 tailwind.config.js,允许 Tailwind 控制当前目录下所有后缀为 html 的文件

    /** @type {import('tailwindcss').Config} */
    module.exports = {
      content: ['./dist/*.{html, js}'],
      theme: {
        extend: {},
      },
      plugins: [],
    }
    
  16. 在根目录创建 postcss.config.js 文件,用于配置 PostCSS

    const tailwindcss = reuqire('tailwind');
    
    module.exports = {
        plugins: [
            'postcss-preset-env',
            tailwindcss
        ],
    };
    
  17. 在 src 目录创建 style.css 作为主 CSS 文件

    @tailwind base;
    @tailwind components;
    @tailwind utilities;
    
  18. 修改 src/index.js,将 style.css 添加到入口文件

    import './style.css'
    

-End-

热门相关:子不语·夜行郎   宠物坟场2   视死如归魏君子   来自异世界的诺诺   越境鬼医