likes
comments
collection
share

听说你还不会 Tailwind CSS(进阶·下篇)

作者站长头像
站长
· 阅读数 19

1. 前言

基础篇:

进阶篇:

经过初始化后,在根目录下有一个 tailwind.config.ts 文件:

import type { Config } from "tailwindcss";

const config: Config = {
  content: [
    "./pages/**/*.{js,ts,jsx,tsx,mdx}",
    "./components/**/*.{js,ts,jsx,tsx,mdx}",
    "./app/**/*.{js,ts,jsx,tsx,mdx}",
  ],
  theme: {
    extend: {
      backgroundImage: {
        "gradient-radial": "radial-gradient(var(--tw-gradient-stops))",
        "gradient-conic":
          "conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))",
      },
    },
  },
  plugins: [],
};
export default config;

上面就是 Tailwind CSS 的配置文件,这篇文章主要讲解 theme 配置项,利用它来实现样式的扩展。

2. content

content 配置项将会接收一个数组,表示应用 Tailwind CSS 的文件范围:

  • "./pages/**/*.{js,ts,jsx,tsx,mdx}" 👉 ./pages 目录下无限级别子目录中的所有以 js、ts、jsx、tsx、mdx 结尾的文件
  • "./components/**/*.{js,ts,jsx,tsx,mdx}" 👉 ./components 下无限级别子目录中的所有以 js、ts、jsx、tsx、mdx 结尾的文件
  • "./app/**/*.{js,ts,jsx,tsx,mdx}" 👉 ./app 下无限级别子目录中的所有以 js、ts、jsx、tsx、mdx 结尾的文件

其中,**/* 表示该目录下的无限级别子目录。

3. theme

theme 在之前已经遇到过,使用 theme() 函数可以获取 Tailwind 默认的样式变量,比如:颜色搭配、字体、边框、响应式断点等等内容。

3.1 覆盖原样式

默认情况下,初始化时就会生成默认的配置内容,具体看这里

如果说要覆盖掉默认的样式,比如,覆盖掉默认颜色:

import type { Config } from 'tailwindcss';

const config: Config = {
  // ...
  theme: {
    colors: {
      blue: '#1fb6ff',
      purple: '#7e5bef',
      pink: '#ff49db',
      orange: '#ff7849',
      green: '#13ce66',
      yellow: '#ffc82c',
      'gray-dark': '#273444',
      gray: '#8492a6',
      'gray-light': '#d3dce6',
    },
  },
};
export default config;

colors 用于定义默认颜色,因此想要使用的颜色应该写在那里。使用看看:

<pre class="text-blue">blue: &apos;#1fb6ff&apos;</pre>
<pre class="text-purple">purple: &apos;#7e5bef&apos;</pre>
<pre class="text-pink">purple: &apos;#ff49db&apos;</pre>

听说你还不会 Tailwind CSS(进阶·下篇)

上面代码中的 &apos; 表示 HTML 中的 '

由于覆盖了 colors 对象的配置,原来的默认颜色就不起作用了,比如下面的 red-200 就不起作用:

<p class="text-red-200">text-red-200 没有效果</p>

听说你还不会 Tailwind CSS(进阶·下篇)

尽管 colors 的值被覆盖了,但是其他的配置不受影响,比如 spacing,它们继续继承默认值。

3.2 扩展原样式

更多的时候,我们希望使用 Tailwind 的便利,同时添加更多的选择。比如,想要追加一些新的颜色,那么就在 extend 对象中添加:

import type { Config } from 'tailwindcss';

const config: Config = {
  // ...
  theme: {
    // ...
    extend: {
      colors: {
        'primary-dark': '#1f2937',
        'primary-light': '#f3f4f6',
        'secondary-dark': '#1f2937',
        'secondary-light': '#f3f4f6',
      },
    },
  },
};
export default config;

然后使用这些新增的颜色:

<p class="text-primary-dark">primary-dark</p>
<p class="text-primary-light bg-primary-dark">primary-dark</p>
<p class="text-secondary-dark">primary-dark</p>
<p class="text-secondary-light bg-secondary-dark">primary-dark</p>

听说你还不会 Tailwind CSS(进阶·下篇)

3.3 可扩展的关键词

除了 colors,之前的文章中提到的 spacing,又或者是控制响应式 screens,也都可以被覆盖或扩展。下面是一张完整的样式声明配置及其对应关系的描述表格:

关键词描述
accentColorValues for the accent-color property
animationValues for the animation property
ariaValues for the aria property
aspectRatioValues for the aspect-ratio property
backdropBlurValues for the backdropBlur plugin
backdropBrightnessValues for the backdropBrightness plugin
backdropContrastValues for the backdropContrast plugin
backdropGrayscaleValues for the backdropGrayscale plugin
backdropHueRotateValues for the backdropHueRotate plugin
backdropInvertValues for the backdropInvert plugin
backdropOpacityValues for the backdropOpacity plugin
backdropSaturateValues for the backdropSaturate plugin
backdropSepiaValues for the backdropSepia plugin
backgroundColorValues for the background-color property
backgroundImageValues for the background-image property
backgroundOpacityValues for the background-opacity property
backgroundPositionValues for the background-position property
backgroundSizeValues for the background-size property
blurValues for the blur plugin
borderColorValues for the border-color property
borderOpacityValues for the borderOpacity plugin
borderRadiusValues for the border-radius property
borderSpacingValues for the border-spacing property
borderWidthValues for the borderWidth plugin
boxShadowValues for the box-shadow property
boxShadowColorValues for the boxShadowColor plugin
brightnessValues for the brightness plugin
caretColorValues for the caret-color property
colorsYour project's color palette
columnsValues for the columns property
containerConfiguration for the container plugin
contentValues for the content property
contrastValues for the contrast plugin
cursorValues for the cursor property
divideColorValues for the divideColor plugin
divideOpacityValues for the divideOpacity plugin
divideWidthValues for the divideWidth plugin
dropShadowValues for the dropShadow plugin
fillValues for the fill plugin
flexValues for the flex property
flexBasisValues for the flex-basis property
flexGrowValues for the flex-grow property
flexShrinkValues for the flex-shrink property
fontFamilyValues for the font-family property
fontSizeValues for the font-size property
fontWeightValues for the font-weight property
gapValues for the gap property
gradientColorStopsValues for the gradientColorStops plugin
gradientColorStopPositionsValues for the gradient-color-stop-positions property
grayscaleValues for the grayscale plugin
gridAutoColumnsValues for the grid-auto-columns property
gridAutoRowsValues for the grid-auto-rows property
gridColumnValues for the grid-column property
gridColumnEndValues for the grid-column-end property
gridColumnStartValues for the grid-column-start property
gridRowValues for the grid-row property
gridRowEndValues for the grid-row-end property
gridRowStartValues for the grid-row-start property
gridTemplateColumnsValues for the grid-template-columns property
gridTemplateRowsValues for the grid-template-rows property
heightValues for the height property
hueRotateValues for the hueRotate plugin
insetValues for the top, right, bottom, and left properties
invertValues for the invert plugin
keyframesKeyframe values used in the animation plugin
letterSpacingValues for the letter-spacing property
lineHeightValues for the line-height property
listStyleTypeValues for the list-style-type property
listStyleImageValues for the list-style-image property
marginValues for the margin property
lineClampValues for the line-clamp property
maxHeightValues for the max-height property
maxWidthValues for the max-width property
minHeightValues for the min-height property
minWidthValues for the min-width property
objectPositionValues for the object-position property
opacityValues for the opacity property
orderValues for the order property
outlineColorValues for the outline-color property
outlineOffsetValues for the outline-offset property
outlineWidthValues for the outline-width property
paddingValues for the padding property
placeholderColorValues for the placeholderColor plugin
placeholderOpacityValues for the placeholderOpacity plugin
ringColorValues for the ringColor plugin
ringOffsetColorValues for the ringOffsetColor plugin
ringOffsetWidthValues for the ringOffsetWidth plugin
ringOpacityValues for the ringOpacity plugin
ringWidthValues for the ringWidth plugin
rotateValues for the rotate plugin
saturateValues for the saturate plugin
scaleValues for the scale plugin
screensYour project's responsive breakpoints
scrollMarginValues for the scroll-margin property
scrollPaddingValues for the scroll-padding property
sepiaValues for the sepia plugin
skewValues for the skew plugin
spaceValues for the space plugin
spacingYour project's spacing scale
strokeValues for the stroke property
strokeWidthValues for the stroke-width property
supportsValues for the supports property
dataValues for the data property
textColorValues for the text-color property
textDecorationColorValues for the text-decoration-color property
textDecorationThicknessValues for the text-decoration-thickness property
textIndentValues for the text-indent property
textOpacityValues for the textOpacity plugin
textUnderlineOffsetValues for the text-underline-offset property
transformOriginValues for the transform-origin property
transitionDelayValues for the transition-delay property
transitionDurationValues for the transition-duration property
transitionPropertyValues for the transition-property property
transitionTimingFunctionValues for the transition-timing-function property
translateValues for the translate plugin
sizeValues for the size property
widthValues for the width property
willChangeValues for the will-change property
zIndexValues for the z-index property

4. 预处理器的使用

在上一篇中有朋友评论:

听说你还不会 Tailwind CSS(进阶·下篇)

4.1 postcss-nesting

官方推荐的 postcss-nesting 插件可以满足嵌套的需求。首先安装依赖:

npm install -D postcss-nesting

然后放进 postcss 处理器配置中(postcss.config.mjs):

/** @type {import('postcss-load-config').Config} */
const config = {
  plugins: {
    'tailwindcss/nesting': 'postcss-nesting',
    tailwindcss: {},
  },
};

export default config;

现在使用一下子,在 global.css 中添加以下代码:

/* ... */

@layer utilities {
  .container {
    @apply w-[1280px] mx-auto;
    span {
      @apply text-lg text-blue;
    }
  }
}

.container 用于控制容器内容居中,span 元素嵌套在其中。

<div class="container bg-gray-light">
  <p>
    Lorem ipsum <span>dolor</span> sit amet, consectetur adipisicing elit.
    Sit accusamus incidunt, minima eligendi delectus sint facere cum,
    placeat dolorum rem debitis <span>doloribus</span> dolore nesciunt
    ratione laudantium <span>doloribusstop</span>enim error architecto
    odio!
  </p>
</div>

听说你还不会 Tailwind CSS(进阶·下篇)

实测有效。

4.2 就是想用 Sass

笔者头铁,笔者就是想用 Sass!

听说你还不会 Tailwind CSS(进阶·下篇)

也不是不行,不过需要知道一件事:预处理器(Sass 之类的)和 Tailwind CSS 是在不同的阶段处理的。预处理器首先处理其输入文件并生成 CSS,然后 Tailwind CSS 和 PostCSS 在预处理器生成的 CSS 上继续处理。

也就是说,不能把 Tailwind 的 theme() 函数的输出传给一个 Sass 的颜色函数,比如:

.error {
  background-color: darken(theme('colors.red.500'), 10%);
}
.btn:hover {
  background-color: light(theme('colors.red.500'), 10%);
}

darken($color, $amount)lighten($color, $amount) 就是 Sass 中的颜色函数。由于 Sass 在 Tailwind 之前运行,还未生成 CSS,因此 theme() 并不可用。

以 React 和 Sass 为例,有 Demo.module.scss 如下:

.container {
  @apply w-[1280px] mx-auto;
  span {
    @apply text-lg text-blue;
  }
}

.title {
  // @apply text-4xl font-bold;
  font-size: 36px;
  line-height: 40px;
  font-weight: bold;
}

.success {
  background-color: theme('colors.green');
}

引入到组件中使用:

import styles from './Demo.module.scss';

export default function Page() {
  return (
    <div>
      <div className={styles.container}>
        <h1 className={styles.title}>hello</h1>
        <p>
          Lorem ipsum <span>dolor</span> sit amet, consectetur adipisicing elit.
          Sit accusamus incidunt, minima eligendi delectus sint facere cum,
          placeat dolorum rem debitis <span>doloribus</span> dolore nesciunt
          ratione laudantium <span>doloribusstop</span>enim error architecto
          odio!
        </p>
        <p className={styles.success}>
          Lorem ipsum dolor, sit amet consectetur adipisicing elit. Corporis,
          maiores eos. Aliquam reiciendis, totam eos deserunt earum, quos velit
          quo magnam temporibus quaerat voluptate expedita nostrum eligendi
          aspernatur fuga harum!
        </p>
      </div>
    </div>
  );
}

听说你还不会 Tailwind CSS(进阶·下篇)

5. 总结

除此以外, Tailwind 还有更多的配置项,如 pluginspresetsprefix 等等,这些内容不需要特别去看,只要知道它们可以做什么,用到时检索即可。下面用一句话分别概括:

  • plugins:添加自定义插件以扩展 Tailwind 的功能。
  • presets:自定义预设样式,多个项目可共享一套配置。
  • prefix:为所有 Tailwind 生成的 utilities 类添加前缀,帮助避免命名冲突。
  • important:配置所有 utilities 类标记为**!important**,确保它们优先应用。
  • corePlugins:禁用某些不想用的样式,减小 CSS 体积。

总结一下,想要覆盖样式使用 theme.key 去覆盖,想要扩展更多则使用 theme.extend.key ,可用的 key 在 3.3 节中;另外使用嵌套语法,还是推荐 postcss-nesting 而不是直接使用 Sass 等预处理器,一方面它的构建速度更快,另一方面仅通过 @tailwind、@apply、theme() 等 Tailwind 关键词的组合就能达到相同的效果。反之,使用预处理器就要考虑语法、执行顺序等等情况,变相增加了开发者的心智负担。

以上就是进阶篇的所有内容,掌握了这些在一般的项目开发已经完全够用了,下篇将讲解响应式相关内容,让你用一套代码搞定多端的 UI 显示。

转载自:https://juejin.cn/post/7371649020123152384
评论
请登录