5分钟了解Tailwindcss

2,109 阅读6分钟

Hi, 我是 Lem, 最近在学习Tailwindcss,进行了下学习记录:

前言

Tailwindcss 的工作原理是扫描所有 HTML 文件、 JavaScript 组件和任何其他类名模板,生成相应的样式,然后将它们写入静态 CSS 文件。

它快速、灵活、可靠ーー零运行时。

安装

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init

配置 postcss

// postcss.config.js
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  }
}

配置 tailwind.config.js

module.exports = {
  content: ['./src/**/*.{html,tsx}'],
  theme: {
    extend: {},
    colors: {
      font20: '20px',
      fontColor: '#1f1f1f'
    }
  },
  plugins: [],
}

Tailwindcss 通过的内置模块

// main.css
@tailwind base;
@tailwind components;
@tailwind utilities;

结合 vscode 一起使用vscode-tailwindcss

// setting.json
{
	"tailwindCSS.emmetCompletions": true,
  "editor.quickSuggestions": {
    "strings": true
  },
  "tailwindCSS.includeLanguages": {
    "html": "HTML",
    "javascript": "javascript",
    "javascriptreact": "javascriptreact",
    "typescript": "typescript",
    "typescriptreact": "typescriptreact",
  },
  "css.validate": false,
}

核心概念

基础知识

使用内置的工具类: 了解更多

p-0padding: 0
mt-10margin-top: 10rem
w-pxwidth: 1px
w-4width: 1rem
<button class="mt-10">
  Save changes
</button>

使用任意值如:mt-[117px]

<button class="mt-[117px]"> // => margin-top: 117px
  Save changes
</button>

处理悬停、焦点和其他状态

Tailwind中的每个实用程序类都可以通过在类名的开头添加修饰符来有条件地应用,该修饰符描述了您想要的元素中。

例如,要在hover上应用bg-sky-700 class,使用hover:bg-sky-700 class:

// html
<button class="bg-sky-500 hover:bg-sky-700">
  Save changes
</button>

// main.css
.bg-sky-500 {
  background-color: #0ea5e9;
}
.hover:bg-sky-700:hover {
  background-color: #0369a1;
}

在 Tailwind 中,默认状态和悬停状态使用单独的类

响应式设计

使用响应性实用工具变体构建自适应用户界面。

Tailwind 中的每个实用程序类都可以有条件地应用于不同的断点,这使得构建复杂的响应性界面变得轻而易举,而无需离开 HTML。

默认情况下有五个断点,灵感来自常见的设备分辨率:

Breakpoint prefixMinimum widthCSS
sm640px@media (min-width: 640px) { ... }
md768px@media (min-width: 768px) { ... }
lg1024px@media (min-width: 1024px) { ... }
xl1280px@media (min-width: 1280px) { ... }
2xl1536px@media (min-width: 1536px) { ... }
<!-- Width of 16 by default, 32 on medium screens, and 48 on large screens -->
<img class="w-16 md:w-32 lg:w-48" src="...">

针对一个特定范围

默认情况下,md: flex 等规则应用的样式将应用于该断点,并保持应用于较大的断点。

如果你只想在一个特定的断点范围处于活动状态时应用一个实用程序,那么你可以使用一个带 max-* 修饰符的响应修饰符(比如 md)来将这个样式限制在一个特定的范围内:

<div class="md:max-xl:flex">
  <!-- ... -->
</div>

Tailwind 生成一个相应的max - *修饰符

ModifierMedia query
max-sm@media not all and (min-width: 640px) { ... }
max-md@media not all and (min-width: 768px) { ... }
max-lg@media not all and (min-width: 1024px) { ... }
max-xl@media not all and (min-width: 1280px) { ... }
max-2xl@media not all and (min-width: 1536px) { ... }

复用样式

Tailwind 鼓励实用程序优先的工作流,其中设计仅使用低级实用程序类实现。这是一种避免过早抽象和随之而来的痛点的有效方法。

当然,随着项目的增长,您将不可避免地发现自己重复常见的实用程序组合,以便在许多不同的地方重新创建相同的设计。

使用@apply提取类

// html
<button class="btn-primary">
  Save changes
</button>

// main.css
@layer components {
  .btn-primary {
    @apply py-2 px-4 font-semibold rounded-lg shadow-md focus:outline-none focus:ring-2 focus:ring-opacity-75;
  }
}

定义和使用样式

将您自己的自定义样式添加到 Tailwind 的最佳实践。

Tailwind 包括一个专业制作的默认调色板开箱即用,详情

配置颜色变量示例:

// tailwind.config.js
module.exports = {
  theme: {
    colors: {
      transparent: 'transparent',
      current: 'currentColor',
      'white': '#ffffff',
      'purple': '#3f3cbb',
      'midnight': '#121063',
      'metal': '#565584',
      'tahiti': '#3ab7bf',
      'silver': '#ecebff',
      'bubble-gum': '#ff77e9',
      'bermuda': '#78dcca',
      'tahiti': {
        100: '#cffafe',
        200: '#a5f3fc',
        DEFAULT: '#06b6d4',
      }
    },
  },
}

默认情况下,在使用颜色的框架中,这些颜色将随处可用,如文本颜色实用工具、边框颜色实用工具、背景颜色实用工具等。

嵌套键将与父键组合在一起,形成类名,如 bg-tahiti-100。

与 Tailwind 中的许多其他地方一样,当您想要定义一个没有后缀的值时,可以使用特殊的 DEFAULT 键:

<div class="bg-midnight text-tahiti">
  <!-- ... -->
</div>

任意值

<button class="bg-[#1da1f2]">
  <svg><!-- ... --></svg>
  Share on Twitter
</button>

使用默认颜色

const colors = require('tailwindcss/colors')

module.exports = {
  theme: {
    colors: {
      transparent: 'transparent',
      current: 'currentColor',
      black: colors.black,
      white: colors.white,
      gray: colors.gray,
      emerald: colors.emerald,
      indigo: colors.indigo,
      yellow: colors.yellow,
    },
  },
}

扩展其他颜色

module.exports = {
  theme: {
    extend: {
      colors: {
        brown: {
          50: '#fdf8f6',
          100: '#f2e8e5',
          200: '#eaddd7',
          300: '#e0cec7',
          400: '#d2bab0',
          500: '#bfa094',
          600: '#a18072',
          700: '#977669',
          800: '#846358',
          900: '#43302b',
        },
      }
    },
  },
}

使用 css 变量进行配置

// main.css
@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {
  :root {
    --color-primary: 255 115 179;
    --color-secondary: 111 114 185;
    /* ... */
  }
}

// tailwind.config.js
module.exports = {
  theme: {
    colors: {
      // Using modern `rgb`
      primary: 'rgb(var(--color-primary) / <alpha-value>)',
      secondary: 'rgb(var(--color-secondary) / <alpha-value>)',

      // Using modern `hsl`
      primary: 'hsl(var(--color-primary) / <alpha-value>)',
      secondary: 'hsl(var(--color-secondary) / <alpha-value>)',

      // Using legacy `rgba`
      primary: 'rgba(var(--color-primary), <alpha-value>)',
      secondary: 'rgba(var(--color-secondary), <alpha-value>)',
    }
  }
}

自定义您的主题

module.exports = {
  theme: {
    screens: {
      sm: '480px',
      md: '768px',
      lg: '976px',
      xl: '1440px',
    },
    colors: {
      'blue': '#1fb6ff',
      'pink': '#ff49db',
      'orange': '#ff7849',
      'green': '#13ce66',
      'gray-dark': '#273444',
      'gray': '#8492a6',
      'gray-light': '#d3dce6',
    },
    fontFamily: {
      sans: ['Graphik', 'sans-serif'],
      serif: ['Merriweather', 'serif'],
    },
    extend: {
      spacing: {
        '128': '32rem',
        '144': '36rem',
      },
      borderRadius: {
        '4xl': '2rem',
      }
    }
  }
}

使用 CSS 和 @layer

@tailwind base;
@tailwind components;
@tailwind utilities;

.my-custom-style {
  background-color: #0369a1;
  color: #ccc;
}

@layer components {
  .my-custom-style {
    @apply text-bermuda;

    background-color: #0369a1;
  }
}

添加基础样式

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {
  h1 {
    @apply text-2xl;
  }
  h2 {
    @apply text-xl;
  }
  /* ... */
}

添加 component classes

@layer components {
  .card {
    background-color: theme('colors.white');
    border-radius: theme('borderRadius.lg');
    padding: theme('spacing.6');
    box-shadow: theme('boxShadow.xl');
  }
  /* ... */
}

添加自定义 utilities

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer utilities {
  .content-auto {
    content-visibility: auto;
  }
}

与预处理器一起使用

TailwindCSS 实际推崇的是不离开html 、少样式代码甚至零样式代码 。 预处理器是为了让开发人员更快书写样式代码,而TailwindCSS旨在消除样式代码,既然开发人员都不用写样式代码了,感觉就不太需要与处理器了。

当然,你也可以和预处理器一起使用:using-with-preprocessors

如果仍然需要使用嵌套语法,怎么办?

TailwindCSS 封装了postcss-nestedpostcss-nesting插件,postcss.config.js文件中加入以下代码:

module.exports = {
  plugins: {
    'tailwindcss/nesting': {}, // [!code focus]
    tailwindcss: {},
    autoprefixer: {},
  },
}

实际上,当你在sass/scss/less/styl文件中使用Tailwind语法时,可能会发生错误的预期甚至错误,因为TailwindCSS的某些语法可能会与预处理器的语法冲突,如在sass文件中使用theme函数会得到不同的预期,因为sass中也存在这个函数,而这种写法会让sass预处理器优先处理这个函数,而实际的期望是希望后处理器来处理。

结论

TailwindCSS 有统一的有规律的命名,通过内置模块,提高我们开发效率,可减少样式文件,结合 postcss 安装和使用,使用成本不是很高,很值得尝试,尤其是 react 项目中,一切皆js。

但引入以下基础样式后,项目打包会增加少量样式包体积(6.5k)

参考

antfu.me/posts/reima…

juejin.cn/post/720078…

公众号链接:web5分钟