css rem 单位_了解和使用CSS中的rem单位

css rem 单位

Gain an in-depth understanding of rem units in CSS, a relative sizing unit with excellent browser support, and learn how to use them effectively.

深入了解CSS中rem单元(具有出色浏览器支持的相对大小调整单元),并学习如何有效地使用它们。

什么是雷姆单位? (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.

在收听广播或音乐播放器之前,您可能遇到过“ REM”一词。 与音乐同伴不同,它们在深度睡眠期间被称为“快速眼动”,而CSS rem则代表“ root em”。 他们不会使您失去宗教信仰,也不会相信月球上的人。 他们可以做的是帮助您实现和谐均衡的设计。

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

根据W3C规范 ,一个rem单位的定义是:

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.

等于根元素上font-size的计算值。 当在根元素的font-size属性中指定时,rem单位将引用该属性的初始值。

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

这意味着1rem等于html元素的字体大小(对于大多数浏览器而言,其默认值为16px)。

Rem单位对Em单位 (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:

em单位的主要问题是它们与自己元素的字体大小有关。 因此,它们会级联并导致意外的结果。 让我们考虑以下示例,在此示例中,如果根字体大小是默认的16px ,则我们希望列表的字体大小为12px

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 case 9px). We can still overcome this problem by using something along these lines:

如果我们有一个嵌套在另一个列表中的列表,则内部列表的字体大小将为其父字体大小的75%(在本例中为9px )。 我们仍然可以通过以下方式克服此问题:

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:

使用rem单位,事情变得更简单:

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.

由于所有大小都是从根字体大小引用的,因此不再需要在单独的声明中覆盖嵌套大小写。

带Rem单位的字体大小 (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.

使用rem单位进行字体大小调整的先驱之一是Jonathan Snook,他在2011年5月发表了REM字体大小调整文章。像许多其他CSS开发人员一样,他不得不面对em单位带来的复杂布局问题。

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.

当时,较旧版本的IE仍占有较大的市场份额,因此无法缩放带有像素大小的文本。 但是,正如我们前面所看到的,使用em单元很容易迷失嵌套并获得意想不到的结果。

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:

使用rem进行字体大小调整的主要问题是使用这些值有些困难。 让我们看一个以rem单位表示的常见字体大小的示例,当然,假定基本大小为16px:

  • 10px = 0.625rem

    10px = 0.625rem
  • 12px = 0.75rem

    12px = 0.75rem
  • 14px = 0.875rem

    14px = 0.875rem
  • 16px = 1rem (base)

    16px = 1rem(基本)
  • 18px = 1.125rem

    18px = 1.125rem
  • 20px = 1.25rem

    20px = 1.25rem
  • 24px = 1.5rem

    24px = 1.5rem
  • 30px = 1.875rem

    30px = 1.875rem
  • 32px = 2rem

    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:

如我们所见,这些值对于进行计算不是很方便。 因此,Snook使用了一个名为“ 62.5% ”的技巧。 无论如何,这并不是一个新发现,因为它已经与em单元一起使用:

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:

由于rem单位是相对于根元素的,因此Snook解决方案的变体变为:

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:

一个还必须考虑其他不支持rem的浏览器。 因此,上面的代码实际上是这样编写的:

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.

尽管此解决方案似乎接近“黄金法则”的地位,但有人建议不要盲目使用它。 哈里·罗伯茨(Harry Roberts) 就使用rem单位发表了自己的看法 。 在他看来,尽管62.5%的解决方案使计算更加容易(因为px中的字体大小是其rem值的10倍),但最终迫使开发人员显式重写其网站中的所有字体大小。

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.

第三种观点来自CSS-Tricks的Chris Coyier。 他的解决方案利用了到目前为止我们遇到的所有三个单元。 他保留了px定义的根大小,使用rem单位定义的模块以及保留了em大小的模块中的元素。 这种方法使操作全局大小变得更容易,它可以缩放模块中的类型,而模块内容是根据模块字体大小本身来缩放的。 路易斯·拉扎里斯(Louis Lazaris) 在CSS中的em单元的力量中讨论了后者的概念。

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

在下面的示例中,您可以看到Chris的方法如何:

See the Pen One Method for Using ems and rems in CSS by SitePoint (@SitePoint) on CodePen.

请参阅CodePenSitePoint ( @SitePoint ) 在CSS中使用em和rems的笔式方法

In practice, there are major frameworks such as Bootstrap 4 and the Material Design guidelines that use rem units for sizing text content.

实际上,存在一些主要框架,例如Bootstrap 4Material Design指南,这些框架使用Rem单元确定文本内容的大小。

A special mention goes to Material-UI, a very popular collection of React components. Not only are they sizing text the same way, but also offer a mechanism to implement the “10px simplification” we mentioned above.

特别要提到的是Material-UI ,这是React组件非常流行的集合。 它们不仅以相同的方式调整文本大小,而且还提供了一种实现我们上面提到的“ 10px简化”的机制。

Another recent project, Every Layout, combines em and rem units in a very inspired way. It comes closest to Chris Coyier’s model outline earlier and it uses em units to emphasize inline elements like SVG icons, spans or other similar elements.

最近的另一个项目Every Layout以一种非常受启发的方式将em和rem单元结合在一起。 它与Chris Coyier的模型轮廓最接近,并且使用em单位强调内联元素,例如SVG图标,跨度或其他类似元素。

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

如您所见,没有“银弹”解决方案。 可能的组合仅受开发人员的想象力限制。

将rems与Media Query Breakpoints一起使用 (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.

在媒体查询中使用em或rem单位与“最佳行长”的概念及其对阅读体验的影响密切相关。 2014年9月,《粉碎杂志》(Smashing Magazine)发表了一篇关于网页排版的综合研究报告,名为《 尺寸问题:在响应式网页设计中平衡行长和字体大小》 。 在许多其他有趣的事情中,文章给出了最佳行长的估计值:介于45到75-85个字符之间(包括空格和标点符号),其中65个为“理想”目标值。

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:

使用1rem = 1个字符的粗略估计,我们可以采用移动优先的方法来控制单列内容的文本流:

.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):

但是,关于rem和em单位用作媒体查询单位时,有一个有趣的细节:它们始终保持相同的值1rem = 1em =浏览器设置的字体大小。 媒体查询规范 (添加了重点)中说明了这种现象的原因:

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.

媒体查询中的相对单位基于初始值,这意味着单位永远不会基于声明的结果。 例如,在HTML中, em单位是相对于font-size的初始值的,它由用户代理或用户的首选项定义,而不是页面上的任何样式

Let’s see a quick example of this behavior:

让我们看一下这种行为的简单示例:

View Media Query Demo on CodePen

在CodePen上查看媒体查询演示

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

首先,在HTML中,我们有一个<span>元素,我们将在其中写入视口的宽度:

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):

接下来,我们有两个媒体查询,一个带有rem单位,另一个带有em单位(为简单起见,使用Sass):

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 = 48px */
}
}

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

最后,我们使用一些jQuery在页面上显示视口宽度,并在窗口大小更改时更新值:

$('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.

我们以62.5%的技巧开始,以表明修改后的根字体大小对用于媒体查询的值没有任何影响。 当我们更改浏览器窗口的宽度时,我们可以看到第一个媒体查询以320px(20×16px)开始,而第二个媒体查询以480px(30×16px)开始活动。 我们声明的font-size更改都不会影响断点。 更改媒体查询断点值的唯一方法是在浏览器设置中修改默认字体大小。

For this reason, it doesn’t really matter if we use em or rem units for media query breakpoints. Zurb Foundation (currently at v6.5.3 at the moment this was written) makes use of em units in the media queries.

因此,我们是否将em或rem单位用于媒体查询断点并不重要。 Zurb Foundation (在撰写本文时当前为v6.5.3)在媒体查询中使用em单位。

无障碍探索 (The Quest for Accessibility)

We’ve seen above that the ability to scale based on the root font size makes rem units very useful for accessibility. Google developers make the recommendation to use relative units for text sizing.

上面我们已经看到,基于根字体大小进行缩放的功能使rem单元对于可访问性非常有用。 Google开发人员建议使用相对单位进行文本大小调整

There is an empirical study run by the people behind the Internet Archive showing that there is a significant amount of users who change their default font size in the browser settings. By using rem and other relative units you respect the users’ decisions about the way they want to browse the web.

Internet档案后面的人进行了一项实证研究,结果表明,有大量用户在浏览器设置中更改其默认字体大小。 通过使用rem和其他相关单位,您可以尊重用户对他们想要浏览网络的方式的决定。

使用rem单位缩放文档 (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.

我们可以找到的Rem单元的第三个用途是构建可伸缩的组件。 通过以rem为单位表示宽度,边距和填充,可以创建随根字体大小而增长或缩小的界面。 让我们通过几个示例来看看这件事是如何工作的。

Using rem Units for Scaling Documents Demo #1

使用rem单元缩放文档演示#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.

在第一个示例中,我们使用媒体查询来更改根字体大小。 就像在上一节中一样,目的是自定义所用设备的阅读体验。 当使用rem表示元素填充值和边距时,整个组件随器件尺寸而缩放。

Let’s see another:

让我们看看另一个:

See the Pen Dynamic Sizing of Modules with Rem Units by SitePoint (@SitePoint) on CodePen.

请参见CodePen上的SitePoint ( @SitePoint )通过Rem单位对模块进行 Pen 动态调整大小

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.

在第二个示例中,我们使用JavaScript进行了相同的更改。 这次,用户可以控制界面的大小,并根据自己的需要进行调整。 添加一种存储这些自定义值的方法(使用数据库,Cookie或本地存储),您便可以基于用户首选项来拥有个性化系统。

结论 (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.

我们在这里结束对CSS rem单元的了解。 显然,在我们的代码中使用这些单元有很多优点,例如响应性,可伸缩性,改进的阅读体验以及在定义组件方面更大的灵活性。 Rem单元不是通用的万能解决方案,但是通过精心部署,它们可以解决许多困扰开发人员多年的问题。 发挥rems的全部潜力取决于我们每个人。 开始您的编辑器,进行实验并与我们其他人分享您的结果。

For more on CSS sizing units, see:

有关CSS大小调整单位的更多信息,请参见:

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

css rem 单位

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值