1. em: 是相对于父元素的 font-size
<div>
<p></p>
</div>
<style>
div{
font-size: 14px;
}
p{
width: 1em; /*实际宽度 14px。 多少em,就是父元素的font-size多少倍 */
height: 1em; /* 实际高度 14px */
background-color: black;
}
</style>

2. rem是根据html根元素的font-size
可以理解为是html的font-size的多少倍数, 1rem就是一倍,2rem就是两倍
----也就是说只需要通过控制html的font-size就可以改变页面中元素的大小
注意: rem只适用于固定尺寸; 该使用 百分比 or flex布局的地方正常使用百分比 or flex来布局
<style>
html {
font-size: 14px;
}
p{
width: 2rem; /*实际宽度 28px。 多少rem,就是html的font-size多少倍 */
height: 2rem;
background-color: orange;
}
</style>

rem适配方案思路:
一.按照设计稿与设备宽度的比例,动态计算并设置html的font-size;
二.设计稿元素的宽,高的取值,按照同等比例换算为rem单位的值;
常见尺寸 iphone4/5: 逻辑像素/css像素320px; iphone6/7/8/x: 逻辑像素375px;
iphone6/7/8Plus: 逻辑像素414px;
1.如 设计稿750px(css像素的两倍)
2.如我们把屏幕划分为15等份(也可以是10,20份),每份作为html字体大小;
3.在750px设备的时候,html字体大小:750/15 = 50px;
在320px设备的时候,html字体大小:320/15 = 21.33px;
4.如div设计稿中宽100px,高100px,rem取值就是:100px / 50(html的font-size) = 2rem;
so 代码中应该写: div{ width:2rem; height:2rem }
<style>
html{ font-size: 50px; } /*默认 pc端打开时,限定为(50px*15rem<body.width)750px。需在最上面 */
@media screen and (min-width: 320px){
html{ font-size: 21.333px; }
}
@media screen and (min-width: 360px){
html{ font-size: 24px; }
}
@media screen and (min-width: 375px){
html{ font-size: 25px; }
}
@media screen and (min-width: 400px){
html{ font-size: 26.666px; }
}
@media screen and (min-width: 414px){
html{ font-size: 27.6px; }
}
@media screen and (min-width: 424px){
html{ font-size: 28.266px; }
}
@media screen and (min-width: 480px){
html{ font-size: 32px; }
}
@media screen and (min-width: 540px){
html{ font-size: 36px; }
}
@media screen and (min-width: 720px){
html{ font-size: 48px; }
}
@media screen and (min-width: 750px){
html{ font-size: 50px; }
}
body{
margin: 0 auto;
min-width: 320px;
width: 15rem; /* 为什么不设置max-width? */
/* because: 50px(html默认font-size) * 15(rem) = 750px;也就是最大宽度*/
/*当320屏幕 21.33(font-size)*15(rem)=320px,会自动缩放 */
/*当375屏幕 25(font-size)*15(rem)=375px, 会自动缩放 */
}
body{ /*原本应该这样写*/
margin: 0 auto;
min-width: 320px;
max-width: 750px;
width:15rem;
}
div{
width: 2rem;
height: 2rem;
background: orange;
}
</style>


5.总结rem的取值公式: 元素rem取值 = 元素在750设计稿的px值 / html font-size;
ps: 一般由设计师按照设备像素/物理像素(750px)为单位制作设计稿。但也有直接用逻辑像素提供(375px,此时只需要*2即可)
网友评论