在移动端比如手机,ipad等设备上浏览网页或者应用的时候,往往会因为分辨率不同而需要做一些自适应的配置才能使网页在各设备上的展现一致。
本文分享一种移动端自适应布局方案。
1、使用js根据设备屏幕大小设置根元素html的font-size
2、元素宽度高度等使用rem
原理分析
以横屏750px的设计稿为例,我们要在屏幕上显示750px的设计稿。那么网页默认的font-size为16px。所以整个网页宽度就是750/16 rem。为了方便,我们设置font-size为100px。那么整个网页宽度就是750/100 =7.5rem。也就是说1rem=100px。
因为7.5rem是一个相对单位。所以我们可以让所有的设备统一,相当于动态缩放html的font-size来实现设计稿的效果。需要做的就是根据设备宽度动态设置html的font-size:
<script>
document.querySelector('html').style.fontSize = window.screen.width / 7.5 + 'px';
window.onresize = function () {
document.querySelector('html').style.fontSize = window.screen.width / 7.5 + 'px';
}
</script>
然后我们在写css的时候使用less或者scss写一个函数。把px转化成rem
@function p2r($size) { //此位scss的语法。less的可自行百度
@return $size / 100 * 1rem;
}
在样式中使用
.btn {
background-image: url(../../images/home/arrow.png);
background-size: 100% 100%;
width: p2r(98);
height: p2b(38);
position: fixed;
bottom: 1%;
left: 50%;
transform: translateX(-50%);
z-index: 2;
}