Date
Oct. 25th, 2024
 
2024年 9月 23日

Post: CSS: rem

CSS: rem

Published 12:11 Nov 01, 2015.

Created by @ezra. Categorized in #Programming, and tagged as #CSS.

Source format: Markdown

Table of Content

最近花了点时间修改博客的页面效果,第一次用 CSS 里的 rem 单位,顺便总结一下。

我们知道,在设置字体时常见的 pxem

px

px 是很常用的单位,比较稳定和精确,但也存在一些问题,例如当用户改变了浏览器字体胆小时如果使用 px 为单位,就会打乱页面布局,为了解决这样的问题,我们有了 em 单位。

em

em 值是相对于父元素的值,在使用 em 时需要知道其父元素的属性,或者设置为 1em

body {
    font-size: 50%;
    /*10 ÷ 20 × 100% = 50%*/
}
h1 {
    font-size: 2.4em;
    /*2.4em × 10 = 24px */
}
p {
    font-size: 1.0em;
    /*1.0em × 10 = 10px */
}

使用 em 的计算公式为:

1 ÷ 父元素font-size × 像素值 = em值

rem

rem 在 W3C 官网的描述是 font size of the root element,也就是说 rem 是相对于根元素的值。

px2em

顺便介绍一个相关的网站 PXtoEM.com

html {
    font-size: 62.5%;
    /*10 ÷ 16 × 100% = 62.5%*/
}
body {
    font-size: 1.4rem;
    /*1.4 × 10px = 14px */
}
h1 {
    font-size: 2.4rem;
    /*2.4 × 10px = 24px*/
}
Pinned Message
HOTODOGO
The Founder and CEO of Infeca Technology.
Developer, Designer, Blogger.
Big fan of Apple, Love of colour.
Feel free to contact me.
反曲点科技创始人和首席执行官。
开发、设计与写作皆为所长。
热爱苹果、钟情色彩。
随时恭候 垂询