rem移动端屏幕适配
rem移动端屏幕适配方法
首先我们知道,rem是相对于根元素html的字体大小font-size的一种相对单位,html的font-size,就相当于是1rem;
例子
html设置100px相当于1rem,所以body设置0.16rem就相当于16px
html{
font-size: 100px;
}
body{
font-size: 0.16rem;
/* font-size: 16px; */
}
实现方法
只需要在使用rem时在不同设备屏幕尺寸下设置根元素的font-size即可;
常见的方法可以使用css媒体查询@media也可以用js来处理
- css
@media only screen and (min-width: 320px){
html {
font-size: calc(100px * 320px / 375px) !important;
}
}
@media only screen and (min-width: 375px){
html {
font-size: calc(100px) !important;
}
}
@media only screen and (min-width: 640px){
html {
font-size: calc(100px * 640px / 375px) !important;
}
}
@media only screen and (min-width: 750px){
html {
font-size: calc(100px * 750px / 375px) !important;
}
}
- javascript
function setHtmlFontSize() {
// 1. 当前屏幕的宽度
var windowWidth = document.documentElement.offsetWidth;
// 最大屏幕和最小屏幕
if (windowWidth > 750) {
windowWidth = 750;
} else if (windowWidth < 320) {
windowWidth = 320;
}
//2. 标准屏幕宽度
var StandardWidth = 375;
// 标准屏幕的html的字体大小
var StandardHtmlFontSize = 100;
//3. 当前屏幕需要设置的根元素的字体大小
var htmlFontSize = windowWidth / StandardWidth * StandardHtmlFontSize;
//4. 把当前计算的html 字体大小设置到页面的html元素上就可以
document.querySelector('html').style.fontSize = htmlFontSize + 'px';
}
//调试的话可以加个resize
// window.addEventListener('resize', setHtmlFontSize)
setHtmlFontSize();
备注一下,写移动端h5页面的时候一定要加上下面这行代码
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />