媒体查询@media、百分比%、pxtorem、相对视窗宽高vw/wh、弹性布局flex
一、媒体查询
解决各端自适应、需要编写多套样式
@media screen and (max-width: 960px){
body{}
}
@media screen and (max-width: 768px){
body{}
}
@media screen and (max-width: 550px){
body{}
}
二、百分比
height、width、top、bottom、left、right、padding、margin,都是相对于父元素
border-radius相对于自身宽度
三、rem
rem是根元素font-size
全局pxtorem方案
npm i postcss-pxtorem
rem.js:
/**
* 用于屏幕适配,根据设计稿宽度是750px配置1 rem单位等于多少px单位。
* 在样式表中可以使用rem单位设置大小,但是手动计算rem比较繁琐,为了快捷编写样式,直接写设计稿的px单位,本项目配置了插件
* 'postcss-pxtorem'与脚本'./postcss.config.js',所以使用设计稿的px单位和数值吧。
*/
const scale = 750 / 75; // 计算配合'./postcss.config.js'的'postcss-pxtorem'中rootValue数值
const resetRem = () => {
const clientWidth = document.documentElement.clientWidth;
const fontSize = `${clientWidth / scale }px`;
const htmlElement = document.getElementsByTagName('html')[0];
const bodyElement = document.getElementsByTagName('body')[0];
htmlElement.style.fontSize = fontSize;
bodyElement.style.fontSize = fontSize;
};
const init = () => {
window.addEventListener('resize', resetRem, false);
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', resetRem, false);
}
};
init();
main.js导入rem.js
postcss.config.js:
module.exports = {
plugins: {
'autoprefixer': {}, // 这里在.browserslistrc中配置
'postcss-pxtorem': {
rootValue: 75, // 配合'./src/utils/rem.js'使用
unitPrecision: 5,
propList: ['*'],
selectorBlackList: ['mint-ui', 'mint-','passtorem-', 'van-', 'vant-', 'vanui', 'vantui'],//白名单
replace: false,
mediaQuery: false,
minPixelValue: 0
}
}
};
四、vw/wh
相对于视窗的宽度,视窗宽度是100vw
相对于视窗的高度,视窗高度是100vh
类似百分比、1px = (1/分辨率宽度)*100vw