基于windicss在项目中的样式管理
前言:本篇主要总结windicss与scss结合使用的方法。总体使用的管理方式采用scss的样式管理方式。
因此只是在使用scss与windicss结合的基础上共同采用scss管理样式的方式管理样式文件。
scss样式管理方式:
1.配置自定义属性
新建 Windi CSS 配置文件
import { defineConfig } from 'vite-plugin-windicss'
export default defineConfig({
attributify: {
prefix: 'w:'//为防止命名冲突自定义前缀
},
alias: {
hstack: 'flex items-center',
vstack: 'flex flex-col',
icon: 'w-6 h-6 fill-current',
app: 'text-red',
'app-border': 'border-gray-200 dark:border-dark-300'
},
theme: {
extend: {
backgroundImage: theme => ({
'app-bg': 'url('@app/src/assets/img/bg.svg')',//自定义样式属性
}),
},
}
})
例:
<div w:bg="app-bg" w:w="full" w:h="full" w:pos="relative"></div>//得到占满全屏的图片
// w:配置中自定义前缀 app-bg:配置中自定义属性
配置自定义断点
// 自定义断点
export default defineConfig({
theme: {
screens: {
phone: '320px',
iPad: '1024px',
},
},
})
使用:
<div class="phone:bg-red-400 phone:text-light-100 phone:p-10 iPad:p-50 iPad:bg-blue-700 ">
响应式
</div>
利用shortcut处理重复使用的样式
你应用程序的任何地方使用,而不需要重复写相同的样式代码 1.在配置文件中
export default {
theme: {
/* ... */
},
shortcuts: {
'btn': 'py-2 px-4 font-semibold rounded-lg shadow-md',
'btn-green': 'text-white bg-green-500 hover:bg-green-700',
},
}
// 在html节点中添加类名即可获得样式
<div class="btn hover:btn-green"></div>
@apply指令使scss结合windicss
例:
<div class="btn btn-blue">button</div>
<style scoped lang="scss">
.btn {
@apply font-bold py-2 px-4 rounded w-100px m-10px;
}
.btn-blue {
@apply bg-blue-500 hover:bg-blue-700 text-white;
padding-top: 1rem;
}
</style>
@variants生成屏幕可变修饰(如:鼠标停留时改变文字颜色等)
例:实现鼠标hover或focus时btn大小扩大一倍
<div class="btn-blue btn">button</div>
.btn {
@apply font-bold py-2 px-4 rounded w-100px m-10px;
}
@variants focus, hover { /** <== */
.btn {
@apply w-200px h-200px;
}
}
同时·还可以通过以下方式实现状态改变
<div class="btn-blue">button</div>
<style scoped lang="scss">
.btn-blue {
@apply bg-blue-500 hover:bg-blue-700 text-white;//(实现hover时背景颜色的改变)
padding-top: 1rem;
}
</style>
@screen引用断点(可以理解为yuscss结合的方式为断点处设置样式)
<style scoped lang="scss">
@screen iPad {
.custom {
@apply bg-blue-500;//在ipad断点处为此条件下设置类名为custom的内容背景色为蓝色
}
}
</style>
利用theme来通过 . 运算符获取设置的值
<div class="color-blue">theme</span>
<style lang="scss" scoped>
.color-blue {
color: theme("colors.blue.400");
}
</style>
利用@layer指令解决样式层叠问题
页面复杂样式繁多时,需要使用优先级权重高的选择器覆盖样式,而@layer提前定义好优先级层级
用法: 1.表示base层级最低,utilities层级最高
@layer base,components,utilities;
2.使用时 最终字体颜色展示为绿色 虽然base写在utilities 之后但定义@layer时 untilities在base之后因此 untilities 的优先级更高
@layer utilities {
.item {
color: green;
}
}
@layer base {
.item {
color: red;
}
}