Appearance
层
CSS 的顺序会影响其优先级。虽然引擎会保留规则的顺序,但有时你可能希望将一些工具类分组,以便显式控制它们的顺序。
使用方法
与提供三个固定层(base
、components
、utilities
)的 Tailwind CSS 不同,UnoCSS 允许你根据需要定义层。要设置层,你可以将元数据作为规则的第三个参数传入:
ts
rules: [
[/^m-(\d)$/, ([, d]) => ({ margin: `${d / 4}rem` }), { layer: 'utilities' }],
// when you omit the layer, it will be `default`
['btn', { padding: '4px' }],
]
这将生成:
css
/* layer: default */
.btn { padding: 4px; }
/* layer: utilities */
.m-2 { margin: 0.5rem; }
每个预检(preflight)也可以设置层:
ts
preflights: [
{
layer: 'my-layer',
getCSS: async () => (await fetch('my-style.css')).text(),
},
]
排序
你可以通过以下方式控制层的顺序:
ts
layers: {
'components': -1,
'default': 1,
'utilities': 2,
'my-layer': 3,
}
未指定顺序的层将按字母顺序排序。
当你希望在各层之间插入自定义 CSS 时,你可以更新入口模块:
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 级联层:
ts
outputToCssLayers: true
你可以通过以下方式更改 CSS 层名称:
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.
}
}
使用变体创建层
可以使用变体创建层。
uno-layer-<name>:
可用于创建一个 UnoCSS 层。
html
<p class="uno-layer-my-layer:text-xl">text</p>
css
/* layer: my-layer */
.uno-layer-my-layer\:text-xl{ font-size:1.25rem; line-height:1.75rem; }
layer-<name>:
可用于创建一个 CSS @layer。
html
<p class="layer-my-layer:text-xl">text</p>
css
/* layer: default */
@layer my-layer{ .layer-my-layer\:text-xl{ font-size:1.25rem; line-height:1.75rem; } }