Vue2 和 Vue3 常见 CSS 样式归纳总结
Vue2 和 Vue3 常见 CSS 样式归纳总结
一、基础样式设置方式
Vue2 & Vue3 通用方式
-
内联样式
<div style="color: red; font-size: 16px;"></div>
-
对象语法
<div :style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
-
数组语法
<div :style="[baseStyles, overridingStyles]"></div>
-
单独的CSS文件
<style scoped> .my-class { color: blue; } </style>
二、布局相关样式
1. Flex布局 (最常用)
.container {display: flex;justify-content: center; /* 主轴对齐方式 */align-items: center; /* 交叉轴对齐方式 */flex-direction: row; /* 主轴方向: row|row-reverse|column|column-reverse */flex-wrap: wrap; /* 换行: nowrap|wrap|wrap-reverse */gap: 10px; /* 子项间距 */
}
2. Grid布局
.container {display: grid;grid-template-columns: repeat(3, 1fr);grid-gap: 20px;
}
3. 定位
.position-example {position: relative; /* relative|absolute|fixed|sticky */top: 10px;left: 20px;z-index: 10;
}
Tips: 各个布局的区别以及示例
三、常用UI样式
1. 盒模型
.box {width: 100px;height: 100px;padding: 10px;margin: 15px;border: 1px solid #ddd;border-radius: 4px;box-sizing: border-box; /* content-box|border-box */box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
2. 文字样式
.text {font-size: 16px;font-weight: bold; /* normal|bold|100-900 */color: #333;line-height: 1.5;text-align: center; /* left|right|center|justify */text-decoration: none; /* underline|line-through|none */
}
3. 背景样式
.bg-example {background-color: #f5f5f5;background-image: url('image.png');background-size: cover; /* contain|cover|100% 100% */background-position: center;background-repeat: no-repeat;
}
四、交互样式
1. 悬停效果
.button {transition: all 0.3s ease;
}
.button:hover {transform: translateY(-2px);box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}
2. 动画
@keyframes fadeIn {from { opacity: 0; }to { opacity: 1; }
}
.fade-in {animation: fadeIn 0.5s ease forwards;
}
3. 禁用状态
.button:disabled {opacity: 0.6;cursor: not-allowed;
}
五、Vue特有样式特性
1. Scoped CSS (Vue2 & Vue3)
<style scoped>
/* 只作用于当前组件 */
</style>
2. CSS Modules (Vue2 & Vue3)
<style module>
/* 生成唯一类名 */
</style>
3. Vue3特有特性
<style>/* 全局样式 */
</style><style scoped>/* 组件作用域样式 */
</style><style module>/* CSS模块 */
</style>
六、响应式样式
1. 媒体查询
@media (max-width: 768px) {.container {flex-direction: column;}
}
2. Vue响应式样式绑定
<template><div :class="{ 'active': isActive, 'error': hasError }"></div><div :style="{ fontSize: responsiveSize + 'px' }"></div>
</template>
七、实用工具类 (推荐使用Tailwind CSS等)
<div class="flex justify-between items-center p-4"></div>
总结建议
- Vue2/Vue3通用:基本CSS写法相同,主要区别在于样式作用域的实现方式
- 推荐组合:
- 布局:Flex/Grid
- 间距:margin/padding/gap
- 颜色:统一使用CSS变量定义主题色
- 动画:transition简单动画,复杂动画用CSS keyframes
- 样式组织:
- 组件样式使用scoped
- 全局样式单独管理
- 常用工具类可提取为全局样式
掌握这些常用样式,可以覆盖Vue项目中90%的样式需求。