From 7c9ae40f51c7873249e9be457889ae0fd4422330 Mon Sep 17 00:00:00 2001 From: Jay Date: Sat, 7 May 2016 16:38:39 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=20px=20em=20rem=20=E6=96=87?= =?UTF-8?q?=E7=AB=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 7 +++-- share/px-em-rem.md | 67 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 2 deletions(-) create mode 100644 share/px-em-rem.md diff --git a/README.md b/README.md index ab7aa16..1a32122 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,8 @@ * 基础 * [前端工具](share/front-tools.md) * [认识 HTML](share/html.md) - * [HTML meta](share/html-meta.md) * [神奇的 CSS](share/amazing-css.md) + * [`px` vs `em` vs `rem`](share/px-em-rem.md) * [SASS](share/sass.md) * [你所不知道的 JavaScript](share/javascript.md) * [ES6 vs ES5](share/es6vs5.md) @@ -43,9 +43,12 @@ * Webpack * UML * Scrum 敏捷 - * transition与visibility + * transition 与 visibility * CSS3 媒体查询 * SVG * Canvas * Promise 编程 + * [HTML meta](share/html-meta.md) + * WebSocket + * HTML viewport diff --git a/share/px-em-rem.md b/share/px-em-rem.md new file mode 100644 index 0000000..181342d --- /dev/null +++ b/share/px-em-rem.md @@ -0,0 +1,67 @@ +# px、em、rem +`px`、`em`和`rem`都是网页设计中的长度单位。`px`是最常用的单位,它是 Pixel 的缩写代表像素,它是计算机图像显示的最小单位;`em`(font size of the element)它是一个相对大小的单位,它的大小会相对于它的父级元素的字体大小;`rem`(font size of the root element)它也是一个相对大小的单位,但是它相对于根元素字体的大小; + +## px +`px`单位就不用多解释了,非常常见。 + +## em +`em`是为了解决长度单位在不同缩放比例下浏览器中能够更好的显示的问题,它是一个相对大小的单位,但是它是相对于其父级元素的大小,这样导致了一个问题,在现在复杂的网页下,层层嵌套的元素最终导致很难控制大小。 + +``` +html { + font-size: 62.5%; /*10 ÷ 16 × 100% = 62.5%*/ +} + +body { + font-size: 1.2em; /*1.2em × 10 = 12px */ +} + +p { + font-size: 1.2em; /*1.2em × ? = ? */ +} +``` + +上面的例子我们可以看到,浏览器默认字体大小为`16px`,`html`的字体大小为`16px * 62.5% = 10px`;`body`的字体大小相对于`html`元素,计算出来为`12px`;但是`p`的大小很难计算,因为我们不知道它的父级元素的字体大小到底是多少,它的父级元素字体大小可能是`12px`、也有可能是`20px`,它太难控制了。 + +## rem +CSS3 的出现让我们对相对的尺寸有了更加稳定的设置方法:那就是`rem`。`rem`它是相对于根元素来计算大小的: + +``` +html { + font-size: 62.5%; /*10 ÷ 16 × 100% = 62.5%*/ +} + +body { + font-size: 1.2rem; /*1.2rem × 10 = 12px */ +} + +p { + font-size: 1.4rem; /*1.4rem × 10 = 14px */ +} +``` + +这样一来,我们可以很好的来控制长度单位的大小,它是一旦设置就是一个稳定的值;我们经常在响应式设计中采用这样的长度单位,通过媒体查询可以让长度单位更加符合不同屏幕大小: + +``` +html { + font-size: 62.5%; /* 10 ÷ 16 × 100% = 62.5% */ +} + +@media screen and (min-width: 400px) { + html { + font-size: 75%; /* 12 ÷ 16 × 100% = 75% */ + } +} + +@media screen and (max-width: 319px) { + html { + font-size: 50%; /* 8 ÷ 16 × 100% = 50% */ + } +} +``` + +## 参考 + +* [CSS Font-Size: em vs. px vs. pt vs. percent](http://kyleschaeffer.com/development/css-font-size-em-vs-px-vs-pt-vs/); +* [Using Points, Pixels, Ems, or Percentages for CSS Fonts](http://webdesign.about.com/cs/typemeasurements/a/aa042803a.htm) +