文章很长,建议耐心看完 : )
1.rem布局
rem(font size of the root element)是指相对于根元素的字体大小的单位。简单的说它就是一个相对单位。
比如:html 的 font-size 设置成了 16 px, 那么 1rem = 16px.
笔者最常用的就是在main.js中引入以下两个文件(一个是移动端适配文件,一个是引用样式重置文件,两个文件都放入src中的assets文件下)
//移动端适配文件
import "./assets/app"
//引用样式重置文件
import "./assets/reset.css"
1.移动端适配文件(app.js)
(function(win) {
var docEl = win.document.documentElement;
var time;
function refreshRem() {
var width = docEl.getBoundingClientRect().width;
if (width > 768) { // 最大宽度
width = 768;
}
var rem = width / 375*100;
docEl.style.fontSize = rem + 'px';
///rem用font-size:100px来进行换算
}
win.addEventListener('resize', function() {
clearTimeout(time);
time = setTimeout(refreshRem, 1);
}, false);
win.addEventListener('pageshow', function(e) {
if (e.persisted) {
clearTimeout(time);
time = setTimeout(refreshRem, 1);
}
}, false);
refreshRem();
})(window);
//getBoundingClientRect();该方法获得页面中某个元素的左,上,右和下分别相对浏览器视窗的位置,他返回的是一个对象,即Object,有6个属性 top 、bottom、right、left、width和height
//以前getBoundingClientRect()是IE特有的,目前FF3+,opera9.5+,safari 4,都已经支持这个方法。
//onpageshow 事件类似于 onload 事件,onload 事件在页面第一次加载时触发, onpageshow 事件在每次加载页面时触发,即 onload 事件在页面从浏览器缓存中读取时不触发。
2.引用样式重置文件(reset.css),可根据自己需求设置
*{margin:0; padding:0;}
li{
list-style: none;
}
a{
text-decoration: none;
color: #333;
}
em,i{
font-style: normal;
}
body{
font-size: .16rem;
}
2.百分比布局
在适配方案中最容易理解的布局方式,不过他有一个限制条件,就是必须知道父元素的宽度,但是我们无法适配高度。
3.flex布局
给父元素设置display:flex
在子元素通过flex参数来设置分局