Skip to content

¥Layers

CSS 的顺序会影响它们的优先级。虽然引擎将 保留规则的顺序,但有时你可能希望对一些工具进行分组以对其顺序进行显式控制。

¥The order of CSS will affect their priorities. While the engine will retain the order of rules, sometimes you may want to group some utilities to have explicit control of their order.

用法

¥Usage

与 Tailwind CSS 提供三个固定图层(basecomponentsutilities)不同,UnoCSS 允许你根据需要定义图层。要设置图层,你可以将元数据作为规则的第三项传递:

¥Unlike Tailwind CSS which offers three fixed layers (base, components, utilities), UnoCSS allows you to define the layers as you want. To set the layer, you can pass the metadata as the third item of your rules:

ts
rules: [
  [/^m-(\d)$/, ([, d]) => ({ margin: `${d / 4}rem` }), { layer: 'utilities' }],
  // when you omit the layer, it will be `default`
  ['btn', { padding: '4px' }],
]

这将生成:

¥This will generate:

css
/* layer: default */
.btn { padding: 4px; }
/* layer: utilities */
.m-2 { margin: 0.5rem; }

还可以在每次预检时设置图层:

¥Layer also can be set on each preflight:

ts
preflights: [
  {
    layer: 'my-layer',
    getCSS: async () => (await fetch('my-style.css')).text(),
  },
]

排序

¥Ordering

你可以通过以下方式控制图层的顺序:

¥You can control the order of layers by:

ts
layers: {
  'components': -1,
  'default': 1,
  'utilities': 2,
  'my-layer': 3,
}

没有指定顺序的图层将按字母顺序排序。

¥Layers without specified order will be sorted alphabetically.

当你想在层之间使用自定义 CSS 时,你可以更新你的入口模块:

¥When you want to have your custom CSS between layers, you can update your entry module:

ts
// 'uno:[layer-name].css'
import 'uno:components.css'

// layers that are not 'components' and 'utilities' will fallback to here
import 'uno.css'

// your own CSS
import './my-custom.css'

// "utilities" layer will have the highest priority
import 'uno:utilities.css'

CSS 级联层

¥CSS Cascade Layers

你可以通过以下方式输出 CSS Cascade Layers:

¥You can output CSS Cascade Layers by:

ts
outputToCssLayers: true

你可以使用以下命令更改 CSS 层名称:

¥You can change the CSS Layer names with:

ts
outputToCssLayers: {
  cssLayerName: (layer) => {
    // The default layer will be output to the "utilities" CSS layer.
    if (layer === 'default')
      return 'utilities'

    // The shortcuts layer will be output to the "shortcuts" sublayer the of "utilities" CSS layer.
    if (layer === 'shortcuts')
      return 'utilities.shortcuts'

    // All other layers will just use their name as the CSS layer name.
  }
}

使用变体的图层

¥Layers using variants

可以使用变体创建图层。

¥Layers can be created using variants.

uno-layer-<name>: 可用于创建 UnoCSS 层。

¥uno-layer-<name>: can be used to create a UnoCSS layer.

html
<p class="uno-layer-my-layer:text-xl">text</p>

/* layer: my-layer */
.uno-layer-my-layer\:text-xl{font-size:1.25rem;line-height:1.75rem;}

layer-<name>: 可用于创建 CSS @layer。

¥layer-<name>: can be used to create a CSS @layer.

html
<p class="layer-my-layer:text-xl">text</p>

/* layer: default */
@layer my-layer{
.layer-my-layer\:text-xl{font-size:1.25rem;line-height:1.75rem;}
}