先简单的一句话介绍一下rem
:
rem
是相对于根元素html
的字号(以px
为单位)来计算宽高的。
rem
布局开发Web App的不错选择。
具体举个例子
html{
font-size:20px;
}
.btn {
width: 6rem;
height: 3rem;
line-height: 3rem;
font-size: 1.2rem;
display: inline-block;
background: #06c;
color: #fff;
border-radius: .5rem;
text-decoration: none;
text-align: center;
}
现在font-size
为20
(即1rem 等于 20px
),效果如下所示:

现在我们把
font-size
设置为50
(即1rem 等于 50px
),效果如下:
在项目中为了方便使用,一般会把
html
的font-size
设置为10
或者是100
。font-size:10px
时,1rem等于10px
,2rem等于20px
,以此类推。
也就是说:
html的font-size可以等比改变所有用了rem单位的元素
那不同分辨率下,怎么办呢?
首先假设上面的页面是按照640的标准尺寸编写的,那么看一个对比图:

通过上边的图表可以看出,如果我们要把640的换成480的,480/640=0.75,那么在480宽度下,其
html
的font-size
也是20px*0.75=15px
,所以如果要适配480的,可将其html
的font-size
也是20px/0.75=26.67px
在项目中,可以通过JS去动态计算根元素的
font-size
,这样的好处是所有设备分辨率都能兼容适配;也可以针对一些主流的屏幕设备去做media query设置’(不能兼容所有设备),如下所示(具体根据实际工作场景确定):
html {
font-size : 20px;
}
@media only screen and (min-width: 401px){
html {
font-size: 25px !important;
}
}
@media only screen and (min-width: 428px){
html {
font-size: 26.75px !important;
}
}
@media only screen and (min-width: 481px){
html {
font-size: 30px !important;
}
}
@media only screen and (min-width: 569px){
html {
font-size: 35px !important;
}
}
@media only screen and (min-width: 641px){
html {
font-size: 40px !important;
}
}
除了兼容不同分辨率的设备之外,项目开发中我们还需要考虑浏览器的兼容性:

未完待续......
网友评论