大约快2年没有写过用户界面,今天接到一个专题的需求,写得比较慢了。以前常用的东西得费死劲才能想起来,自然影响速度。看来还是要总结经验。
拿到的设计稿是3倍图,宽度是1125px,然后怎么用rem来实现自适应。
¶ 怎么来定义1rem的大小
怎么来定义1rem的大小,网上有一大堆关于rem的解释,这里就不说了,上代码。设置1rem = 100px。为什么要设置为100px,下面会说到。
html { font-size: 100px; }
¶ 分析
分析,适配的过程实际就是缩放,也就是比例不会变
屏幕大小 | 设计稿大小 | 1rem的大小 | 说明 |
---|---|---|---|
1125px | 1125px | 100px | 这里就是最初的定义 |
1280px | 1125px | 100px / (1125px / 1280px) | (1125px/1280px)就是计算放大的比例 |
750px | 1125px | 100px / (1125px / 750px) | 计算缩小的比例 |
375px | 1125px | 100px / (1125px / 375px) | 计算缩小的比例 |
¶ 理解对不对,弄个demo验证下
<!DOCTYPE html>
<html lang="zh-cn">
<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,maximum-scale=1.0,minimun-scale=1.0">
<title>关于rem的最佳实践</title>
<style>
html, body { margin: 0; padding: 0; }
html { font-size: 100px; }
.box { width: 11.25rem; background-color: bisque; }
.h1, .h2, .h3 { padding: 0.6rem; }
.h1 { font-size: 1.2rem; }
.h2 { font-size: 0.6rem; }
.h3 { font-size: 0.36rem; }
</style>
</head>
<body>
<div class="box">
<div class="h1">关于rem的最佳实践</div>
<div class="h2">关于rem的最佳实践</div>
<div class="h3">关于rem的最佳实践</div>
</div>
<script>
const setView = () => {
const width = document.body.clientWidth
const designWidth = 1125
const ratio = designWidth / width
const fontSize = 100 / ratio
document.documentElement.style.fontSize = fontSize + 'px'
const h1 = document.querySelector('.h1')
const h2 = document.querySelector('.h2')
const h3 = document.querySelector('.h3')
const arr = []
arr.push({
width,
designWidth,
ratio,
fontSize,
h1: window.getComputedStyle(h1).fontSize,
h2: window.getComputedStyle(h2).fontSize,
h3: window.getComputedStyle(h3).fontSize,
box: document.querySelector('.box').clientWidth
})
console.table(arr)
}
setView()
window.onresize = () => {
setView()
}
</script>
</body>
</html>
¶ 结果看起来不错
补充说明:
这个也是关键代码
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimun-scale=1.0">
¶ 补充说明
比较特别的地方,用媒体查询去做就好了。在媒体查询的css里面直接使用px作为单位会比较好。
<style>
@media (min-device-width: 1000px) {
.h1 { font-size: 120px; }
.h2 { font-size: 60px; }
.h3 { font-size: 36px; }
}
</style>