css 原子化
什么是css 原子化?
CSS 原子化(Atomic CSS)是一种 CSS 设计方法,旨在通过将样式拆分为最小且独立的单位来简化和加速样式的编写和维护。这种方法的核心思想是每个类只应用单一的样式属性,而不是组合样式。
特点
- 每个类名只控制一个样式,比如 bg-red 只设置背景色为红色,text-center 只让文本居中。
- 因为类是高度独立的,可以通过组合多个类来实现复杂的样式,而不必重复定义样式。
- 由于类名简单且可重复使用,能够减少冗余 CSS 代码,有助于减少最终生成的 CSS 文件大小。
- 通过简单的类名命名规则,可以更快速地理解和修改样式。
原子化代表
- tailwind
- bootstrap
- unocss
unocss 与其他两类相比,他的优势是更加的自由,能够自己自定义原子> 化规则,不像其他两类只能使用他们定义的规则
使用unocss
自定义原子化规则
- 安装
npm i unocss -D
- 在
vite.config.ts
中引入
import UnoCSS from 'unocss/vite'
export default defineConfig({
plugins: [UnoCSS()]
})
- 在main.ts中引入
import 'virtual:uno.css'
- 创建配置文件uno.config.ts
import { defineConfig } from 'unocss'
export default defineConfig({})
- 编写自定义规则
import type { Rule } from 'unocss'
// 自定义规则
export const rules = [
['flex', { flex: 'display: flex' }],
['w-100', { width: '100%' }],
['h-100', { height: '100%' }],
[/^p-(\d+)$/, ([, d]) => ({ padding: `${d}px` })]
] as Rule<Object>[]
// 自定义组合
export const shortcut = {
full: 'w-100 h-100'
}
// 主题
export const theme = {
black: 'black', // 表示加上前缀bg/color即可给background和文本设置对应的颜色
white: 'white'
}
- 应用自定义规则
import { rules, shortcut, theme } from './shortcut'
export default defineConfig({
rules,
shortcuts: shortcut,
theme
})
<template>
<div class="flex full bg-black color-white">
<h1 class="p-2">原子化</h1>
<p>unocss</p>
</div>
</template>
使用预设preset
除开我们自己定义原子化规则以外,unocss
还支持我们使用tailwind
的原子化规则
import { defineConfig, presetAttributify, presetUno } from 'unocss'
export default defineConfig({
presets: [
presetAttributify(),
presetUno()
]
})