四、移动适配 - vw
1、适配方案
- 相对单位
- 相对视口的尺寸计算结果
- vw:viewport width
- 1vw = 1/100视口宽度
- vh:viewport height
- 1vh = 1/100视口宽度
示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> * { margin: 0; padding: 0; } /* vw 和 vh 是相对视口宽高计算结果,可以直接实现移动端适配效果 */ /* .box { width: 50vw; height: 30vw; background-color: pink; } */ .box { width: 50vh; height: 30vh; background-color: green; } </style> </head> <body> <div class="box"></div> </body> </html>
2、vw 布局
查看设计稿宽度 → 确定参考设备宽度(视口宽度)→ 确定 vw 尺寸(1/100 视口宽度)
vw单位的尺寸 = px 单位数值 / ( 1/100 视口宽度 )
示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="./demo.css"> </head> <body> <div class="box"></div> </body> </html>
Less 示例:
// .box { // width: (68 / 3.75vw); // height: (29 / 3.75vw); // background-color: pink; // } .box { width: (68 / 6.67vh); height: (29 / 6.67vh); background-color: green; } // px单位尺寸 / 1/100 视口的宽度或高度
3、vh单位问题
- 开发中,vw和vh不能混用。
- vh是1/100视口高度,全面屏视口高度尺寸大,如果混用可能会导致盒子变形