層級
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; }
也可以在每個預設樣式上設定層級
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>
/* 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>
/* layer: default */
@layer my-layer{
.layer-my-layer\:text-xl{font-size:1.25rem;line-height:1.75rem;}
}