【转】Understanding and Using rem Units in CSS

CSS units have been the subject of several articles here on SitePoint (such as A Look at Length Units in CSSThe New CSS3 Relative Font Sizing Units, and The Power of em Units in CSS).

Today we increase the count by having an in-depth look at rem units, which have excellent browser support and a polyfill if you need support for old IE.

More from this author

What Are rem Units?

You might have encountered the term “R.E.M.” before while listening to the radio or your music player. Unlike their musical counterparts, named for the “Rapid Eye Movement” during deep sleep, in CSS rem stands for “root em”. They won’t make you lose your religion nor believe in a man on the moon. What they can do is help you achieve a harmonious and balanced design.

According to the W3C spec the definition for one rem unit is:

Equal to the computed value of font-size on the root element. When specified on the font-size property of the root element, the rem units refer to the property’s initial value.

This means that 1rem equals the font size of the html element (which for most browsers has a default value of 16px).

Rem Units vs. Em Units

The main problem with em units is that they are relative to the font size of their own element. As such they can cascade and cause unexpected results. Let’s consider the following example, where we want lists to have a font size of 12px, in the case where the root font size is the default 16px:

html {
  font-size: 100%;
}

ul {
  font-size: 0.75em;
}

If we have a list nested inside another list, the font size of the inner list will be 75% of the size of its parent (in this case9px). We can still overcome this problem by using something along these lines:

ul ul {
  font-size: 1em;
}

This does the trick, however we still have to pay a lot of attention to situations where nesting gets even deeper.

With rem units, things are a simpler:

html {
  font-size: 100%;
}

ul {
  font-size: 0.75rem;
}

As all the sizes are referenced from the root font size, there is no more need to cover the nesting cases in separate declarations.

Font Sizing with Rem Units

One of the pioneers of using rem units for font sizing is Jonathan Snook with his Font sizing with REM article, back in May, 2011. Like many other CSS developers, he had to face the problems that em units bring in complex layouts.

At that time, older versions of IE still had large market shares and they were unable to zoom text that was sized with pixels. However, as we saw earlier, it is very easy to lose track of nesting and get unexpected results with em units.

The main issue with using rem for font sizing is that the values are somewhat difficult to use. Let’s see an example of some common font sizes expressed in rem units, assuming, of course, that the base size is 16px:

  • 10px = 0.625rem
  • 12px = 0.75rem
  • 14px = 0.875rem
  • 16px = 1rem (base)
  • 18px = 1.125rem
  • 20px = 1.25rem
  • 24px = 1.5rem
  • 30px = 1.875rem
  • 32px = 2rem

As we can see, these values are not very convenient for making calculations. For this reason, Snook used a trick called “62.5%“. It was not a new discovery, by any means, as it was already used with em units:

body { font-size:62.5%; }  /* =10px */
h1   { font-size: 2.4em; } /* =24px */
p    { font-size: 1.4em; } /* =14px */
li   { font-size: 1.4em; } /* =14px? */

As rem units are relative to the root element, Snook’s variant of the solution becomes:

html { font-size: 62.5%; }  /* =10px */
body { font-size: 1.4rem; } /* =14px */
h1   { font-size: 2.4rem; } /* =24px */

One also had to take into account the other browsers that didn’t support rem. Thus the code from above would have actually been written this way:

html {
    font-size: 62.5%;
}

body {
    font-size: 14px;
    font-size: 1.4rem;
}

h1 {
    font-size: 24px;
    font-size: 2.4rem;
}

While this solution seems to be close to the status of a “golden rule”, there are people who advise against using it blindingly. Harry Roberts writes his own take on the use of rem units. In his opinion, while the 62.5% solution makes calculation easier (as the font sizes in px are 10 times their rem values), it ends up forcing developers to explicitly rewrite all the font sizes in their website.

A third view comes from Chris Coyier of CSS-Tricks. His solution makes use of all three units we encountered so far. He keeps the root size defined in px, modules defined with rem units, and elements inside modules sized with em. This approach makes easier to manipulate global size, which scales the type in the modules, while the module content is scaled based on the module font size itself. Louis Lazaris discussed that latter concept in The Power of em Units in CSS.

In the example below you can see how Chris’s approach would look:

As you can see, there is no “silver bullet” solution. The combinations possible are limited only by the imagination of the developers.

Using rems with Media Query Breakpoints

The use of em or rem units inside media queries is closely related to the notion of “optimal line length” and how it influences the reading experience. In September 2014, Smashing Magazine published a comprehensive study on web typography called Size Matters: Balancing Line Length And Font Size In Responsive Web Design. Among many other interesting things, the articles gives an estimate for optimal line length: between 45 and 75-85 characters (including spaces and punctuation), with 65 the “ideal” target value.

Using a rough estimate of 1rem = 1character, we can control the flow of text for a single column of content, in a mobile-first approach:

.container {
  width: 100%;
}

@media (min-width: 85rem) {
  .container {
    width: 65rem;
  }
}

There is, however, one interesting detail about rem and em units when used as units for media queries: they always keep the same value of 1rem = 1em = browser-set font size. The reason for this behavior is explained in the media query spec(emphasis added):

Relative units in media queries are based on the initial value, which means that units are never based on results of declarations. For example, in HTML, the em unit is relative to the initial value of font-size, defined by the user agent or the user’s preferences, not any styling on the page.

Let’s see a quick example of this behavior:

View Media Query Demo on CodePen

First, in our HTML, we have a <span> element where we will write the width of the viewport:

Document width: <span></span>px

Next we have two media queries, one with rem units and the other with em units (this uses Sass for simplicity):

html {
  font-size: 62.5%; /* 62.5% of 16px = 10px */

  @media (min-width: 20rem) {
    /* 20*16px = 320px */
    background-color: lemonchiffon;
    font-size: 200%;
    /* 200% of 16px = 32px */
  }

  @media (min-width: 30em) {
    /* 30*16px = 480px */
    background-color: lightblue;
    font-size: 300%; /* 300% of 16px = 30px */
  }
}

Finally, we use a bit of jQuery to display the viewport width on the page, updating the value when the window size changes:

$(‘span‘).text($(window).width());

$(window).on(‘resize‘, function(e) {
  $(‘span‘).text($(window).width());
});

We begin with the 62.5% trick to show that the modified root font size does not have any effect on the values used for the media queries. As we change the width of the browser window we can see that the first media query kicks in at 320px (20 × 16px) while the second one becomes active at 480px (30 × 16px). None of the font-size changes we declared had any effect on the breakpoints. The only way to change the media query breakpoint values is to modify the default font size in the browser settings.

For this reason it doesn’t really matter if we use em or rem units for media query breakpoints. As a matter of fact, bothFoundation v5 and the newly announced Bootstrap v4 alpha use em units for their media queries.

Using rem Units for Scaling Documents

A third use we can find for rem units is to build scalable components. By expressing widths, margins, and padding in rem units, it becomes possible to create an interface that grows or shrinks in tune with the root font size. Let’s see how this thing works using a couple of examples.

Using rem Units for Scaling Documents Demo #1

In this first example, we change the root font size using media queries. Just like in the previous section, the purpose is to customize the reading experience for the device used. As element padding values and margins are expressed using rem, the entire component scales with the device size.

Let’s see another:

In the second example we do the same alteration using JavaScript. This time the user has control over the size of the interface, adjusting it to fit his needs. Add a way to store these custom values (using either a database, cookies or local storage) and you have the base of a personalization system based on user preferences.

Conclusion

We end here our encounter with CSS rem units. It is obvious that there are many advantages in using these units in our code, like responsiveness, scalability, improved reading experience, and greater flexibility in defining components. Rem units not a universal silver bullet solution but, with careful deployment, they can solve many problems that have irked developers for years. It’s up to each one of us to unlock the full potential of rems. Start your editors, experiment and share your results with the rest of us.

It’s not The End of the World as We Know It, rather it’s yet another path on the journey that makes front-end developers “Shiny Happy People“.

转自:https://www.sitepoint.com/understanding-and-using-rem-units-in-css/

时间: 2024-12-18 10:45:27

【转】Understanding and Using rem Units in CSS的相关文章

关于使用rem单位、css函数calc()进行自适应布局

一.关于css中的单位 大家都知道在css中的单位,一般都包括有px,%,em等单位,另外css3新增加一个单位rem. 其中px,%等单位平时在传统布局当中使用的比较频繁,大家也比较熟悉,不过px单位在进行自适应布局的过程当中则会有些力不从心,大部分的解决方案是使用%为单位配合@media媒介查询来进行自适应布局. 不过还有另外一个css3新添加的单位也同样可以拿来进行自适应布局,在我看来这种方法也更加方便直观. 1.em和rem 首先先介绍一下em,这个单位是根据其父元素的字体大小来进行计算

使用rem单位时css sprites的坑

在使用rem单位时,用雪碧图(我不喜欢这个名字!)做背景图片在移动端有时会有错位.pc模拟是没有问题的,而且错位的情况不同的手机还不太一样.这里说几个解决的办法.出现这个问题的原因我找了很久都找不到,再接着找吧! background-size和background-position都用rem 我实际使用中是用这个方法解决问题的.但是据说这样还是会有错位的时候. 转换为px 这个是一定有效的方法.background-size 和 position都用px写死.然后动态增加.zoom{trans

css中单位em和rem

一.介绍 1.em w3cschool中给出css中尺寸单位如下: 单位 描述 % 百分比 in 英寸 cm 厘米 mm 毫米 em 1em 等于当前的字体尺寸. 2em 等于当前字体尺寸的两倍. 例如,如果某元素以 12pt 显示,那么 2em 是24pt. 在 CSS 中,em 是非常有用的单位,因为它可以自动适应用户所使用的字体. ex 一个 ex 是一个字体的 x-height. (x-height 通常是字体尺寸的一半.) pt 磅 (1 pt 等于 1/72 英寸) pc 12 点活

fantasai对新一代CSS开发者的三点建议

原文链接:@siusinng小倩 大家好!欢迎来到上海CSS开发者大会! Welcome to the Shanghai CSS Developers Conference! 我叫fantasai,姓名是Elika Etemad. I am fantasai, also known as Elika Etemad. 我是W3C CSS委员会的一个spec editor:也就是说我编写CSS的技术标准,如CSS Flexbox Level 1和CSS Writing Modes Level 3.

关于CSS需要知道的10件事

原文: http://dsheiko.com/weblog/10-things-to-need-to-know-about-css CSS may look as a simple language. In fact it can be simple only to use, but definitely not simple to maintain. CSS看起来是个简单的语言,实际上只是使用较为简单,但是很显然维护它并不简单. Observing that the maximum numbe

移动端使用rem适配及相关问题

移动端适配方案,说多也很多.可以使用百分比布局,但百分比与em都是基于父元素进行计算的,在实际应用中不是很方便.使用rem不仅可以设置字体大小,块大小也可以设置.而且可以良好的适配各种终端,所以这方案很受欢迎. rem定义及浏览器支持情况 rem(font size of the root element)是指相对于根元素的字体大小的单位.简单的说它就是一个相对单位.看到rem一定会想起em单位,em(font size of the element)是指相对于父元素的字体大小的单位.它们之间其

[翻译]解读CSS中的长度单位

测量,在WEB设计上是非常重要的.在CSS中有至少10种不同的测量单位.每种单位都有其独特的作用,使用它们,可以使页面,在各种设备上,很好的工作.一旦你熟悉了所有这些单位,你可以更准确地设定元素的大小了.这个教程中,我们将看看在CSS中,使用单位的不同,在什么情况下使用什么样的单位,以及如何去使用它们. 绝对长度单位 绝对单位在物理世界真实测量的数字表示.这些单位不依赖于屏幕大小和分辨率.结果就是,绝对长度单位不能很好地在数字设备上使用,或分辨率未知的情况下使用.这种单位更适合,为物理媒介设计时

Sass基础——Rem与Px的转换

rem是CSS3中新增加的一个单位值,他和em单位一样,都是一个相对单位.不同的是em是相对于元素的父元素的font-size进行计算:rem是相对于根元素html的font-size进行计算.这样一来rem就绕开了复杂的层级关系,实现了类似于em单位的功能. Rem的使用 前面说了em是相对于其父元素来设置字体大小的,这样就会存在一个问题,进行任何元素设置,都有可能需要知道他父元素的大小,在我们多次使用时,就会带来无法预知的错误风险.而rem是相对于根元素<html>,这样就意味着,我们只需

Rem与Px的转换[转载]

原文:http://www.w3cplus.com/preprocessor/sass-px-to-rem-with-mixin-and-function.html rem是CSS3中新增加的一个单位值,他和em单位一样,都是一个相对单位.不同的是em是相对于元素的父元素的font-size进行计算:rem是相对于根元素html的font-size进行计算.这样一来rem就绕开了复杂的层级关系,实现了类似于em单位的功能. Rem的使用 前面说了em是相对于其父元素来设置字体大小的,这样就会存在