页面适配
页面适配
布局单位
vw,vh 相对视口大小的百分比大小
px:固定单位
不会随着视口大小改变而改变
不会随着设备屏幕尺寸的大小改变而改变
em,rem:相对单位
em:相对父元素的 font-size 的大小
1em == 父元素的 font-size
2em == 2 _ 父元素的 font-size
rem:相对于根(html)的 font-size 大小
1rem == html 的 font-size 大小
2rem == 2 _ html 的 font-size 大小
自适应布局
淘宝自适应方案:淘宝无限适配
UI 设计图多大:移动端宽度 750px PC 端宽度 1920
前端调试项目以 iPhone6 为基准 宽度 375px
淘宝自适应原理:
html 的 font-size 大小=1rem,因此可以通过改变 html 的 font-size 大小改变所有使用 rem 单位的元素大小
html 的 font-size 初始为 100px,即 100px=1rem。那么 1px=0.01rem 方便计算
当视口变小时,等比缩小 html 的 font-size,即等比缩小 1rem,即等比缩小所有使用 rem 单位的元素
在缩小过程中,浏览器字体最小为 12px,当字体大小缩小到 12px 的时候不会继续缩小
实战演练
效果展示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div class="box">1rem</div>
<div class="box1">2rem</div>
<div class="box2">3rem</div>
<script type="text/javascript">
window.onresize = function () {
// let designSize = 1920; // PC端设计图尺寸
let designSize = 750 // 移动端设计图尺寸
let html = document.documentElement // html节点
let wW = html.clientWidth // 视口宽度
let rem = (wW * 100) / designSize // 计算1rem为多少px
document.documentElement.style.fontSize = rem + 'px' //将计算出的1rem的大小设置给html的font-size
}
</script>
<style>
html {
font-size: 100px;
}
body {
font-size: 0.16rem;
}
.box {
width: 1rem;
height: 1rem;
background: #aaa;
}
.box1 {
width: 2rem;
height: 1rem;
background: #444;
}
.box2 {
width: 3rem;
height: 1rem;
background: red;
}
</style>
</body>
</html>