核心思想(原则)
1.基本原则,布局更多的使用flex,然后尺寸使用rem、vw、vh为单位
2.如果是根据不同屏幕需要使用不同的布局,一般使用通过检测屏幕尺寸换不同的站点或者媒体查询。
解析单位(rem、vw、vh)
1.rem
是以html字体大小为1rem的大小,html为16px,1rem =16px.。rem之所以能自适应就是根据屏幕大小去用js重新设置html的字体大小。
计算方式:html字体大小 = (js获取到的当前设备宽度/设计图宽度)* 设计图宽度下1rem大小
第三方插件可自动转换rem: postcss-pxtorem +js计算
在vue中使用rem
在vue+vite中基本使用:
index.html
<script>
let width = Matn.min(document.body.clientWidth,750) //获取当前的设备宽度(限制最大宽 度750px)
let fontsize = (width/750)*100 //项目中的尺寸需要计算 比如:宽度100px == 100/100 = 1rem
document.documentElement.style.fontSize = fontsize + 'px'
</script>
结合插件 postcss-pxtorem 使用:
1.下载插件 npm install postcss-pxtorem --save
2.在vite中配置(配置后组件样式直接使用px,不需要手动计算)
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import postcsspxtorem from 'postcss-pxtorem'
import { root } from 'postcss'
// https://vitejs.dev/config/
export default defineConfig(() => {
return {
plugins: [vue()],
//scss全局变量的配置
css: {
postcss: {
plugins: [
postcsspxtorem({
rootValue: 100, //UI设计图的宽度/10
unitPrecision: 3, //转rem精确到小数点几位
proList: ['*'], //需要转换的属性,*表示所有
selectorBlackList: ['ignore'], //不进行px转换的选择器
replace: true, //是否直接更换属性值,而不进行添加备用属性
mediaQuery: false, //是否在媒体查询的css代码中也进行转换
minPixeValue: 0, //设置要替换的最小像素值
exclude: /node_modules/i //排除下的文件夹
})
]
}
}
}
})