rem
是CSS3中新增加的一个单位值,他和em
单位一样,都是一个相对单位。不同的是em
是相对于元素的父元素的font-size
进行计算;rem
是相对于根元素html
的font-size
进行计算。这样一来rem
就绕开了复杂的层级关系,实现了类似于em
单位的功能。
Rem的使用
前面说了em
是相对于其父元素来设置字体大小的,这样就会存在一个问题,进行任何元素设置,都有可能需要知道他父元素的大小,在我们多次使用时,就会带来无法预知的错误风险。而rem
是相对于根元素<html>
,这样就意味着,我们只需要在根元素确定一个参考值,这个参考值设置为多少,完全可以根据您自己的需求来定。
假设就使用浏览器默认的字号16px
,来看一些px
单位与rem
之间的转换关系:
| px | rem |
------------------------
| 12 | 12/16 = .75 |
| 14 | 14/16 = .875 |
| 16 | 16/16 = 1 |
| 18 | 18/16 = 1.125 |
| 20 | 20/16 = 1.25 |
| 24 | 24/16 = 1.5 |
| 30 | 30/16 = 1.875 |
| 36 | 36/16 = 2.25 |
| 42 | 42/16 = 2.625 |
| 48 | 48/16 = 3 |
-------------------------
如果你要设置一个不同的值,那么需要在根元素<html>
中定义,为了方便计算,时常将在<html>
元素中设置font-size
值为62.5%
:此时1rem=10px
html {
font-size: 62.5%; /* 10 ÷ 16 × 100% = 62.5% */
}
| px | rem |
-------------------------
| 12 | 12/10 = 1.2 |
| 14 | 14/10 = 1.4 |
| 16 | 16/10 = 1.6 |
| 18 | 18/10 = 1.8 |
| 20 | 20/10 = 2.0 |
| 24 | 24/10 = 2.4 |
| 30 | 30/10 = 3.0 |
| 36 | 36/10 = 3.6 |
| 42 | 42/10 = 4.2 |
| 48 | 48/10 = 4.8 |
-------------------------
或者在<html>
元素中设置font-size
值为312.5%此时1rem=50px,与62.5%相差五倍,
html {
font-size: 312.5%
}
@media screen and (max-width:359px) and (orientation:portrait) {
html {
font-size: 266.67%
}
}
@media screen and (min-width:360px) and (max-width:374px) and (orientation:portrait) {
html {
font-size: 300%
}
}
@media screen and (min-width:384px) and (max-width:399px) and (orientation:portrait) {
html {
font-size: 320%
}
}
@media screen and (min-width:400px) and (max-width:413px) and (orientation:portrait) {
html {
font-size: 333.33%
}
}
@media screen and (min-width:414px) and (max-width:431px) and (orientation:portrait) {
html {
font-size: 345%
}
}
@media screen and (min-width:432px) and (max-width:479px) and (orientation:portrait) {
html {
font-size: 360%
}
}
@media screen and (min-width:480px) and (max-width:639px) and (orientation:portrait) {
html {
font-size: 400%
}
}
@media screen and (min-width:640px) and (orientation:portrait) {
html {
font-size: 533.33%
}
}