Html 我应该在 CSS 中使用 px 还是 rem 值单位?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11799236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 02:03:24  来源:igfitidea点击:

Should I use px or rem value units in my CSS?

htmlcssdistanceunits-of-measurement

提问by josh3736

I am designing a new website and I want it to be compatible with as much browsers and browser settings as possible. I am trying to decide what unit of measurement I should use for the sizes of my fonts and elements, but am unable to find a conclusive answer.

我正在设计一个新网站,我希望它与尽可能多的浏览器和浏览器设置兼容。我正在尝试决定我的字体和元素的大小应该使用什么度量单位,但我无法找到一个决定性的答案。

My question is: should I use pxor remin my CSS?

我的问题是:我应该使用px还是rem在我的 CSS 中?

  • So far I know that using pxisn't compatible with users who adjust their base font size in their browser.
  • I've disregarded ems because they are more of a hassle to maintain, compared to rems, as they cascade.
  • Some say that rems are resolution independent and therefore more desirable. But others say that most modern browsers zoom all elements equally anyway, so using pxis not a problem.
  • 到目前为止,我知道 usingpx与在浏览器中调整基本字体大小的用户不兼容。
  • 我忽略了ems,因为与rems相比,它们在级联时维护起来更麻烦。
  • 有人说rems 与分辨率无关,因此更可取。但是其他人说大多数现代浏览器无论如何都会平等地缩放所有元素,因此使用px不是问题。

I'm asking this because there are a lot of different opinions as to what is the most desirable measure of distance in CSS, and I am not sure which is best.

我问这个是因为对于 CSS 中最理想的距离度量有很多不同的意见,我不确定哪个是最好的。

回答by josh3736

TL;DR:use px.

TL;DR:使用px.

The Facts

事实

  • First, it's extremely important to know that per spec, the CSS pxunit does notequal one physical display pixel. This has alwaysbeen true – even in the 1996 CSS 1 spec.

    CSS defines the reference pixel, which measures the size of a pixel on a 96 dpi display. On a display that has a dpi substantially different than 96dpi (like Retina displays), the user agent rescales the pxunit so that its size matches that of a reference pixel. In other words, this rescaling is exactly why 1 CSS pixel equals 2 physical Retina display pixels.

    That said, up until 2010 (and the mobile zoom situation notwithstanding), the pxalmost always did equal one physical pixel, because all widely available displays were around 96dpi.

  • Sizes specified in ems are relative to the parent element. This leads to the em's "compounding problem" where nested elements get progressively larger or smaller. For example:

    body { font-size:20px; } 
    div { font-size:0.5em; }
    

    Gives us:

    <body> - 20px
        <div> - 10px
            <div> - 5px
                <div> - 2.5px
                    <div> - 1.25px
    
  • The CSS3 rem, which is always relative only to the root htmlelement, is now supported on 96% of all browsers in use.

  • 首先,了解每个规范的 CSSpx单元等于一个物理显示像素非常重要。这一直是正确的——即使在 1996 CSS 1 规范中也是如此

    CSS 定义了参考像素,它测量 96 dpi 显示器上像素的大小。在 dpi 与 96dpi 显着不同的显示器上(如 Retina 显示器),用户代理会重新缩放px单位,使其尺寸与参考像素的尺寸相匹配。换句话说,这种重新缩放正是 1 个 CSS 像素等于 2 个物理 Retina 显示像素的原因。

    也就是说,直到 2010 年(尽管移动变焦情况如此),px几乎总是等于一个物理像素,因为所有广泛使用的显示器都在 96dpi 左右。

  • ems 中指定的大小是相对于父元素的。这会导致em嵌套元素逐渐变大或变小的“复合问题”。例如:

    body { font-size:20px; } 
    div { font-size:0.5em; }
    

    给我们:

    <body> - 20px
        <div> - 10px
            <div> - 5px
                <div> - 2.5px
                    <div> - 1.25px
    
  • CSS3rem始终只与根html元素相关,现在96% 的浏览器都支持

The Opinion

意见

I think everyone agrees that it's good to design your pages to be accommodating to everyone, and to make consideration for the visually impaired. One such consideration (but not the only one!) is allowing users to make the text of your site bigger, so that it's easier to read.

我想每个人都同意设计您的页面以适应每个人并考虑到视障人士是件好事。一个这样的考虑(但不是唯一的!)是允许用户使您的网站的文本更大,以便更容易阅读。

In the beginning, the only way to provide users a way to scale text size was by using relative size units (such as ems). This is because the browser's font size menu simply changed the root font size. Thus, if you specified font sizes in px, they wouldn't scale when changing the browser's font size option.

一开始,为用户提供缩放文本大小的唯一方法是使用相对大小单位(例如ems)。这是因为浏览器的字体大小菜单只是更改了根字体大小。因此,如果您在 中指定字体大小px,则在更改浏览器的字体大小选项时它们不会缩放。

Modern browsers (and even the not-so-modern IE7) all changed the default scaling method to simply zooming in on everything, including images and box sizes. Essentially, they make the reference pixel larger or smaller.

现代浏览器(甚至不那么现代的 IE7)都将默认缩放方法更改为简单地放大所有内容,包括图像和框大小。本质上,它们使参考像素更大或更小。

Yes, someone could still change their browser default stylesheet to tweak the default font size (the equivalent of the old-style font size option), but that's a very esoteric way of going about it and I'd wager nobody1does it. (In Chrome, it's buried under the advanced settings, Web content, Font Sizes. In IE9, it's even more hidden. You have to press Alt, and go to View, Text Size.) It's much easier to just select the Zoom option in the browser's main menu (or use Ctrl++/-/mouse wheel).

是的,有人仍然可以改变自己的浏览器默认样式表来调整默认字体大小(相当于旧风格的字体大小的选项),但是这是绕了一个非常深奥的方式,我敢打赌没有人1做的。(在 Chrome 中,它隐藏在高级设置、Web 内容、字体大小下。在 IE9 中,它更加隐藏。您必须按 Alt,然后转到查看、文本大小。)只需选择缩放选项就容易多了浏览器的主菜单(或使用Ctrl+ +/ -/鼠标滚轮)。

1 - within statistical error, naturally

1 - 在统计误差内,自然

If we assume most users scale pages using the zoom option, I find relative units mostly irrelevant. It's much easier to develop your page when everything is specified in the same unit (images are all dealt with in pixels), and you don't have to worry about compounding. ("I was told there would be no math"– there's dealing with having to calculate what 1.5em actually works out to.)

如果我们假设大多数用户使用缩放选项缩放页面,我发现相对单位大多无关紧要。当所有内容都以同一单位指定时(图像均以像素处理),开发页面会容易得多,而且您不必担心复合。(“我被告知不会有数学”- 不得不计算 1.5em 的实际效果。)

One other potential problem of using only relative units for font sizes is that user-resized fonts may break assumptions your layout makes. For example, this might lead to text getting clipped or running too long. If you use absolute units, you don't have to worry about unexpected font sizes from breaking your layout.

仅使用字体大小的相对单位的另一个潜在问题是用户调整大小的字体可能会破坏您的布局所做的假设。例如,这可能会导致文本被剪切或运行时间过长。如果您使用绝对单位,您就不必担心会破坏您的布局的意外字体大小。

So my answer is use pixel units. I use pxfor everything. Of course, your situation may vary, and if you must support IE6 (may the gods of the RFCs have mercy on you), you'll have to use ems anyway.

所以我的答案是使用像素单位。我px什么都用。当然,您的情况可能会有所不同,如果您必须支持 IE6(可能 RFC 之神会怜悯您),您em无论如何都必须使用s。

回答by zzzzBov

I would like to praise josh3736's answerfor providing some excellent historical context. While it's well articulated, the CSS landscape has changed in the almost five years since this question was asked. When this question was asked, pxwasthe correct answer, but that no longer holds true today.

我要赞扬josh3736 的回答提供了一些极好的历史背景。虽然它的表述很清楚,但自从提出这个问题以来,CSS 格局在近五年内发生了变化。当这个问题被问到时,px正确的答案,但今天不再适用。



tl;dr:use rem

tl;博士:使用rem

Unit Overview

单位概览

Historically pxunits typically represented one device pixel. With devices having higher and higher pixel density this no longer holds for many devices, such as with Apple's Retina Display.

过去,px单位通常代表一个设备像素。随着设备具有越来越高的像素密度,这不再适用于许多设备,例如 Apple 的 Retina Display。

remunits represent the root emsize. It's the font-sizeof whatever matches :root. In the case of HTML, it's the <html>element; for SVG, it's the <svg>element. The default font-sizein every browser* is 16px.

rem单位代表- [ROOT EM大小。它font-size是任何匹配的:root。在 HTML 的情况下,它是<html>元素;对于 SVG,它是<svg>元素。font-size每个浏览器*中的默认值是16px.

At the time of writing, remis supported by approximately 98% of users. If you're worried about that other 2%, I'll remind you that media queries are alsosupported by approximately 98% of users.

在撰写本文时,rem大约 98% 的用户都支持。如果您担心其他 2%,我会提醒您,大约 98% 的用户支持媒体查询

On Using px

关于使用 px

The majority of CSS examples on the internet use pxvalues because they were the de-facto standard. pt, inand a variety of other units couldhave been used in theory, but they didn't handle small values well as you'd quickly need to resort to fractions, which were longer to type, and harder to reason about.

互联网上的大多数 CSS 示例都使用px值,因为它们是事实上的标准。pt,in以及理论上可以使用的各种其他单位,但它们不能很好地处理小值,因为您很快就需要求助于分数,因为打字时间更长,而且更难推理。

If you wanted a thin border, with pxyou could use 1px, with ptyou'd need to use 0.75ptfor consistent results, and that's just not very convenient.

如果你想要一个细边框,px你可以使用1pxpt你需要使用0.75pt以获得一致的结果,这不是很方便。

On Using rem

关于使用 rem

rem's default value of 16pxisn't a very strong argument for its use. Writing 0.0625remis worsethan writing 0.75pt, so why would anyone use rem?

rem的默认值16px不是其使用的有力论据。写作0.0625rem更糟糕的不是写作0.75pt,那么为什么会有人使用rem

There are two parts to rem's advantage over other units.

rem与其他单位相比,有两个方面的优势。

  • User preferences are respected
  • You can change the apparent pxvalue of remto whatever you'd like
  • 尊重用户偏好
  • 您可以将 的表观px值更改为rem您想要的任何值

Respecting User Preferences

尊重用户偏好

Browser zoom has changed a lot over the years. Historically many browsers would only scale up font-size, but that changed pretty rapidly when websites realized that their beautiful pixel-perfect designs were breaking any time someone zoomed in or out. At this point, browsers scale the entire page, so font-based zooming is out of the picture.

多年来,浏览器缩放发生了很大变化。从历史上看,许多浏览器只会放大font-size,但是当网站意识到它们漂亮的像素完美设计在有人放大或缩小时就会崩溃时,这种情况很快发生了变化。此时,浏览器会缩放整个页面,因此基于字体的缩放不在图片范围内。

Respecting a user's wishes is not out of the picture. Just because a browser is set to 16pxby default, doesn't mean any user can't change their preferences to 24pxor 32pxto correct for low vision or poor visibility (e.x. screen glare). If you base your units off of rem, any user at a higher font-size will see a proportionally larger site. Borders will be bigger, padding will be bigger, margins will be bigger, everything will scale up fluidly.

尊重用户的意愿并非不可能。仅仅因为浏览器被16px默认设置为,并不意味着任何用户都不能将他们的偏好更改为24px32px纠正低视力或低能见度(例如屏幕眩光)。如果你的单位基于rem,任何使用更高字体大小的用户都会看到一个比例更大的网站。边框会更大,填充会更大,边距会更大,一切都会流畅地放大。

If you base your media queries on rem, you can also make sure that the site your users see fits their screen. A user with font-sizeset to 32pxon a 640pxwide browser, will effectively be seeing your site as shown to a user at 16pxon a 320pxwide browser. There's absolutely no loss for RWD in using rem.

如果您的媒体查询基于rem,您还可以确保用户看到的网站适合他们的屏幕。在宽浏览器上font-size设置为的用户将有效地看到您的站点,如在宽浏览器上向用户显示的那样。RWD 使用.32px640px16px320pxrem

Changing Apparent pxValue

改变表观px

Because remis based on the font-sizeof the :rootnode, if you want to change what 1remrepresents, all you have to do is change the font-size:

由于rem是基于font-size对的:root节点,如果你想改变什么1rem代表,你所要做的就是改变font-size

:root {
  font-size: 100px;
}
body {
  font-size: 1rem;
}
<p>Don't ever actually do this, please</p>

Whatever you do, don't set the :rootelement's font-sizeto a pxvalue.

无论您做什么,都不要将:root元素设置font-sizepx值。

If you set the font-sizeon htmlto a pxvalue, you've blown away the user's preferences without a way to get them back.

如果您将font-sizeon设置html为一个px值,您就已经破坏了用户的偏好,而没有办法让他们回来。

If you want to change the apparentvalue of rem, use %units.

如果要更改 的表观rem,请使用%单位。

The math for this is reasonably straight-forward.

这个的数学是相当简单的。

The apparent font-size of :rootis 16px, but lets say we want to change it to 20px. All we need to do is multiply 16by some value to get 20.

的明显字体大小:root16px,但假设我们想将其更改为20px。我们需要做的就是乘以16某个值来得到20

Set up your equation:

设置你的方程:

16 * X = 20

And solve for X:

并解决X

X = 20 / 16
X = 1.25
X = 125%

:root {
  font-size: 125%;
}
<p>If you're using the default font-size, I'm 20px tall.</p>

Doing everything in multiples of 20isn't all that great, but a common suggestion is to make the apparent size of remequal to 10px. The magic number for that is 10/16which is 0.625, or 62.5%.

以 的倍数做所有事情20并不是那么好,但一个常见的建议是使 的表观大小rem等于10px。那个神奇的数字10/160.625, 或62.5%

:root {
  font-size: 62.5%;
}
<p>If you're using the default font-size, I'm 10px tall.</p>

The problem now is that your default font-sizefor the rest of the page is set way too small, but there's a simple fix for that: Set a font-sizeon bodyusing rem:

现在的问题是font-size页面其余部分的默认设置太小了,但是有一个简单的解决方法:font-sizebodyusing上设置一个rem

:root {
  font-size: 62.5%;
}

body {
  font-size: 1.6rem;
}
<p>I'm the default font-size</p>

It's important to note, with this adjustment in place, the apparent value of remis 10pxwhich means any value you might have written in pxcan be converted directly to remby bumping a decimal place.

重要的是要注意,通过这种调整,remis的表观值10px意味着您可能写入的任何值都px可以rem通过碰撞小数位直接转换为。

padding: 20px;

turns into

变成

padding: 2rem;

The apparent font-size you choose is up to you, so if you want there's no reason you can't use:

您选择的明显字体大小取决于您,因此如果您愿意,没有理由不能使用:

:root {
  font-size: 6.25%;
}
body {
  font-size: 16rem;
}

and have 1remequal 1px.

并具有1rem相等1px

So there you have it, a simple solution to respect user wishes while also avoiding over-complicating your CSS.

所以你有了它,一个尊重用户意愿的简单解决方案,同时也避免了你的 CSS 过于复杂。

Wait, so what's the catch?

等等,有什么收获?

I was afraid you might ask that. As much as I'd like to pretend that remis magic and solves-all-things, there are still some issues of note. Nothing deal-breaking in my opinion, but I'm going to call them out so you can't say I didn't warn you.

我怕你会问那个。尽管我想假装这rem是魔法并解决所有问题,但仍有一些问题需要注意。在我看来,没有什么破坏交易的行为,但我要把他们叫出来,所以你不能说我没有警告你。

Media Queries (use em)

媒体查询(使用em

One of the first issues you'll run into with reminvolves media queries. Consider the following code:

您将遇到的首要问题之一rem涉及媒体查询。考虑以下代码:

:root {
  font-size: 1000px;
}
@media (min-width: 1rem) {
  :root {
    font-size: 1px;
  }
}

Here the value of remchanges depending on whether the media-query applies, and the media query depends on the value of rem, so what on earth is going on?

这里的值的rem变化取决于媒体查询是否适用,而媒体查询取决于 的值rem,那么到底发生了什么?

remin media queries uses the initial value of font-sizeand should not(see Safari section) take into account any changes that may have happened to the font-sizeof the :rootelement. In other words, it's apparent value is always16px.

rem在媒体查询中使用 的初始值font-size并且不应该(参见 Safari 部分)考虑可能发生font-size:root元素 的任何更改。换句话说,它的表观值总是16px

This is a bit annoying, because it means that you have to do somefractional calculations, but I have found that most common media queries already use values that are multiples of 16.

这有点烦人,因为这意味着您必须进行一些小数计算,但我发现大多数常见的媒体查询已经使用了 16 的倍数的值。

|   px | rem |
+------+-----+
|  320 |  20 |
|  480 |  30 |
|  768 |  48 |
| 1024 |  64 |
| 1200 |  75 |
| 1600 | 100 |

Additionally if you're using a CSS preprocessor, you can use mixins or variables to manage your media queries, which will mask the issue entirely.

此外,如果您使用 CSS 预处理器,您可以使用 mixins 或变量来管理您的媒体查询,这将完全掩盖问题。

Safari苹果浏览器

Unfortunately there's a known bug with Safari where changes to the :rootfont-size do actually change the calculated remvalues for media query ranges. This can cause some very strange behavior if the font-size of the :rootelement is changed within a media query. Fortunately the fix is simple: use emunits for media queries.

不幸的是,Safari 存在一个已知错误,即更改:root字体大小实际上会更改rem媒体查询范围的计算值。如果在:root媒体查询中更改元素的字体大小,这可能会导致一些非常奇怪的行为。幸运的是,修复很简单:使用em媒体查询的单位

Context Switching

上下文切换

If you switch between projects various different projects, it's quite possible that the apparent font-size of remwill have different values. In one project, you might be using an apparent size of 10pxwhere in another project the apparent size might be 1px. This can be confusing and cause issues.

如果您在不同的项目之间切换不同的项目,很可能 的明显字体大小rem将具有不同的值。在一个项目中,您可能会使用表观大小,10px而在另一个项目中,表观大小可能是1px。这可能会令人困惑并导致问题。

My only recommendation here is to stick with 62.5%to convert remto an apparent size of 10px, because that has been more common in my experience.

我在这里唯一的建议是坚持62.5%转换rem为 的明显大小10px,因为这在我的经验中更为常见。

Shared CSS Libraries

共享 CSS 库

If you're writing CSS that's going to be used on a site that you don't control, such as for an embedded widget, there's really no good way to know what apparent size remwill have. If that's the case, feel free to keep using px.

如果您正在编写将在您无法控制的站点上使用的 CSS,例如用于嵌入式小部件,则确实没有什么好方法可以知道rem将具有多大的外观尺寸。如果是这种情况,请随时继续使用px.

If you still want to use remthough, consider releasing a Sass or LESS version of the stylesheet with a variable to override the scaling for the apparent size of rem.

如果您仍然想使用rem,请考虑发布带有变量的样式表的 Sass 或 LESS 版本,以覆盖rem.



* I don't want to spook anyone away from using rem, but I haven't been able to officially confirm that everybrowser uses 16pxby default. You see, there are a lot of browsers and it wouldn't be all that hard for one browser to have diverged ever so slightly to, say 15pxor 18px. In testing, however I have not seen a single example where a browser using default settings in a system using default settings had any value other than 16px. If you find such an example, please share it with me.

* 我不想吓唬任何人使用rem,但我无法正式确认每个浏览器16px默认使用。你看,有很多浏览器,对于一个浏览器来说,如果有如此轻微的分歧,比如15px或,这并不难18px。但是,在测试中,我没有看到一个示例,其中在使用默认设置的系统中使用默认设置的浏览器具有除16px. 如果你找到这样的例子,请与我分享。

回答by uzyn

This articledescribes pretty well the pros and cons of px, em, and rem.

本文介绍了相当不错的优点和缺点pxem以及rem

The author finally concludes that the best method is probably to use both pxand rem, declaring pxfirst for older browsers and redeclaring remfor newer browsers:

作者最后得出结论,最好的方法可能是同时使用pxand rempx首先为旧浏览器声明,rem为新浏览器重新声明:

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

回答by Rolf

As a reflex answer, I would recommend using rem, because it allows you to change the "zoom level" of the whole document at once, if necessary. In some cases, when you want the size to be relative to the parent element, then use em.

作为反射性答案,我建议使用 rem,因为它允许您在必要时立即更改整个文档的“缩放级别”。在某些情况下,当您希望大小相对于父元素时,请使用 em。

Butrem support is spotty, IE8 needs a polyfill, and Webkit is exhibiting a bug. Moreover, sub-pixel calculation can cause things such as one pixel lines to sometimes disappear. The remedy is to code in pixels for such very small elements. That introduces even more complexity.

但是rem 支持参差不齐,IE8 需要一个 polyfill,而 Webkit 出现了一个错误。而且,亚像素计算有时会导致诸如一个像素线之类的东西消失。补救措施是为这种非常小的元素以像素为单位进行编码。这引入了更多的复杂性。

So, overall, ask yourself whether it's worth it - how important and likely it is that you change the "zoom level" of the whole document within CSS?

因此,总的来说,问问自己这是否值得 - 在 CSS 中更改整个文档的“缩放级别”的重要性和可能性有多大?

For some cases it's yes, for some cases it'll be no.

在某些情况下是肯定的,在某些情况下则不是。

So, it depends on your needs, and you have to weight pros and cons, because using rem and em introduces some additional considerations in comparison to the "normal" pixel-based workflow.

因此,这取决于您的需求,您必须权衡利弊,因为与“正常”基于像素的工作流程相比,使用 rem 和 em 会引入一些额外的注意事项。

Keep in mind that it's easy to switch (or rather convert) your CSS from px to rem (JavaScript is another story), because the following two blocks of CSS code would produce the same result:

请记住,将 CSS 从 px 切换(或更确切地说是转换)到 rem 很容易(JavaScript 是另一回事),因为以下两个 CSS 代码块会产生相同的结果:

html {
}

body {
  font-size:14px;
}

.someElement {
  width: 12px;
}


html {
  font-size:1px;
}

body {
  font-size:14rem;
}

.someElement {
  width: 12rem;
}

回答by JerryGoyal

Yes, REM and PX are relativeyet other answers have suggested to go for REM over PX, I would also like to back this up using an accessibility example.
When user sets different font-size on browser, REM automatically scale up and down elements like fonts, images etc on the webpage which is not the case with PX.

是的,REM 和 PX 是相对的,但其他答案建议通过 PX 选择 REM,我还想使用可访问性示例来支持这一点。
当用户在浏览器上设置不同的字体大小时,REM 会自动放大和缩小网页上的字体、图像等元素,而 PX 则不是这种情况。



In the below gif left side text is set using font size REM unit while right side font is set by PX unit.

在下面的 gif 中,左侧文本使用字体大小 REM 单位设置,而右侧字体由 PX 单位设置。

enter image description here

在此处输入图片说明

As you can see that REM is scaling up/down automatically when I resize the default font-size of webpage.(bottom-right side)

如您所见,当我调整网页的默认字体大小时,REM 会自动放大/缩小。(右下角)

Default font-size of a webpage is 16px which is equal to 1 rem (only for default html page i.e. html{font-size:100%}), so, 1.25rem is equal to 20px.

网页的默认字体大小为 16px 等于 1 rem(仅适用于默认 html 页面 ie html{font-size:100%}),因此,1.25rem 等于 20px。

P.S: who else is using REM? CSS Frameworks! like Bootstrap 4, Bulma CSS etc, so better get along with it.

PS:还有谁在使用 REM?CSS 框架!像 Bootstrap 4、Bulma CSS 等,所以最好与它相处。

回答by Joshua Carmody

josh3736's answer is a good one, but to provide a counterpoint 3 years later:

josh3736 的回答很好,但要在 3 年后提供对位:

I recommend using remunits for fonts, if only because it makes it easier for you, the developer, to change sizes. It's true that users very rarely change the default font size in their browsers, and that modern browser zoom will scale up pxunits. But what if your boss comes to you and says "don't enlarge the images or icons, but make all the fonts bigger". It's much easier to just change the root font size and let all the other fonts scale relative to that, then to change pxsizes in dozens or hundreds of css rules.

我建议使用rem单位作为字体,只是因为它使(开发人员)更容易更改大小。确实,用户很少更改浏览器中的默认字体大小,而且现代浏览器缩放会放大px单位。但是如果你的老板来找你说“不要放大图像或图标,而是把所有的字体都放大”怎么办?只需更改根字体大小并让所有其他字体相对于此缩放,然后px在数十或数百个 css 规则中更改大小,就容易多了。

I think it still makes sense to use pxunits for some images, or for certain layout elements that should always be the same size regardless of the scale of the design.

我认为px对某些图像或某些布局元素使用单位仍然有意义,无论设计的比例如何,它们都应该始终保持相同的大小。

Caniuse.com may have said that only 75% of browsers when josh3736 posted his answer in 2012, but as of March 27 they claim 93.78% support. Only IE8 doesn't support it among the browsers they track.

Caniuse.com 在 2012 年 josh3736 发布他的回答时可能说只有 75% 的浏览器,但截至 3 月 27 日,他们声称支持 93.78%。在他们跟踪的浏览器中,只有 IE8 不支持它。

回答by cereallarceny

I've found the best way to program the font sizes of a website are to define a base font size for the bodyand then use em's (or rem's) for every other font-sizeI declare after that. That's personal preference I suppose, but it's served me well and also made it very easy to incorporate a more responsive design.

我发现对网站字体大小进行编程的最佳方法是为 定义一个基本字体大小body,然后为font-size之后声明的每个其他字体使用 em(或 rem)。我想这是个人喜好,但它对我很有用,而且也很容易融入更具响应性的设计

As far as using rem units go, I think it's good to find a balance between being progressive in your code, but to also offer support for older browsers. Check out this link about browser support for rem units, that should help out a good amount on your decision.

至于使用 rem 单位,我认为在代码渐进式和提供对旧浏览器的支持之间找到平衡是很好的。 查看此链接,了解浏览器对 rem 单位的支持,这对您的决定有很大帮助。

回答by Zenexer

ptis similar to rem, in that it's relatively fixed, but almost always DPI-independent, even when non-compliant browsers treat pxin a device-dependent fashion. remvaries with the font size of the root element, but you can use something like Sass/Compass to do this automatically with pt.

pt类似于rem,因为它相对固定,但几乎总是独立于 DPI,即使不兼容的浏览器px以依赖于设备的方式处理也是如此。 rem随根元素的字体大小而变化,但您可以使用 Sass/Compass 之类的工具来自动执行此操作pt

If you had this:

如果你有这个:

html {
    font-size: 12pt;
}

then 1remwould always be 12pt. remand emare only as device-independent as the elements on which they rely; some browsers don't behave according to spec, and treat pxliterally. Even in the old days of the Web, 1 point was consistently regarded as 1/72 inch--that is, there are 72 points in an inch.

那么1rem永远是12ptrem并且em仅与它们所依赖的元素一样独立于设备;有些浏览器的行为不符合规范,而是按px字面意思对待。即使在 Web 的旧时代,1 磅也一直被认为是 1/72 英寸——也就是说,一英寸有 72 磅。

If you have an old, non-compliant browser, and you have:

如果您有一个旧的、不兼容的浏览器,并且您有:

html {
    font-size: 16px;
}

then 1remis going to be device-dependent. For elements that would inherit from htmlby default, 1emwould also be device-dependent. 12ptwould be the hopefullyguaranteed device-independent equivalent: 16px / 96px * 72pt = 12pt, where 96px = 72pt = 1in.

然后1rem将取决于设备。对于html默认继承自的元素,1em也将依赖于设备。 12pt将是有希望的保证与设备无关的等效项:16px / 96px * 72pt = 12pt,其中96px = 72pt = 1in

It can get pretty complicated to do the math if you want to stick to specific units. For example, .75em of html = .75rem = 9pt, and .66em of .75em of html = .5rem = 6pt. A good rule of thumb:

如果您想坚持使用特定单位,则进行数学运算可能会变得非常复杂。例如.75em of html = .75rem = 9pt, 和.66em of .75em of html = .5rem = 6pt。一个好的经验法则:

  • Use ptfor absolute sizes.If you really need this to be dynamic relative to the root element, you're asking too much of CSS; you need a language that compiles to CSS, like Sass/SCSS.
  • Use emfor relative sizes.It's pretty handy to be able to say, "I want the margin on the left to be about the maximum width of a letter," or, "Make this element's text just a bit bigger than its surroundings." <h1>is a good element on which to use a font size in ems, since it might appear in various places, but should always be bigger than nearby text. This way, you don't have to have a separate font size for every class that's applied to h1: the font size will adapt automatically.
  • Use pxfor very tiny sizes.At very small sizes, ptcan get blurry in some browsers at 96 DPI, since ptand pxdon't quite line up. If you just want to create a thin, one-pixel border, say so. If you have a high-DPI display, this won't be obvious to you during testing, so be sure to test on a generic 96-DPI display at some point.
  • Don't deal in subpixels to make things fancy on high-DPI displays.Some browsers might support it--particularly on high-DPI displays--but it's a no-no. Most users prefer big and clear, though the web has taught us developers otherwise. If you want to add extended detail for your users with state-of-the-art screens, you can use vector graphics (read: SVG), which you should be doing anyway.
  • 使用pt绝对大小。如果你真的需要它相对于根元素是动态的,那么你对 CSS 的要求就太多了;你需要一种可以编译成 CSS 的语言,比如 Sass/SCSS。
  • 使用em的相对大小。能够说“我希望左边的边距大约是一个字母的最大宽度”或“使这个元素的文本比它的周围大一点”是非常方便的。 <h1>是一个很好的元素,可以在 em 中使用字体大小,因为它可能出现在不同的地方,但应该总是比附近的文本大。这样,您不必为应用到的每个类都设置单独的字体大小h1:字体大小将自动适应。
  • 使用px了非常微小的尺寸。在非常小的尺寸下,pt在 96 DPI 的某些浏览器中可能会变得模糊,因为ptpx不太对齐。如果您只想创建一个细长的单像素边框,请这么说。如果您拥有高 DPI 显示器,则在测试期间这对您来说不会很明显,因此请务必在某个时候在通用 96-DPI 显示器上进行测试。
  • 不要处理子像素来让高 DPI 显示器看起来很漂亮。某些浏览器可能支持它——尤其是在高 DPI 显示器上——但这是一个禁忌。大多数用户更喜欢大而清晰,尽管网络已经告诉我们开发人员不是这样。如果您想使用最先进的屏幕为您的用户添加扩展细节,您可以使用矢量图形(阅读:SVG),无论如何您都应该这样做。

回答by liljoshu

Half (but only half) snarky answer (the other half is bitter disdain of the reality of bureaucracy):

一半(但只有一半)尖刻的回答(另一半是对官僚主义现实的苦涩不屑):

Use vh

使用 vh

Everything is always sized to browser window.

一切总是按浏览器窗口的大小调整。

Always allow scroll down, never to the side.

始终允许向下滚动,永远不要滚动到一边。

Set body width to be a static 50vh, and nothing floats or breaks out of the parent div. And style only using tables so everything is held rigidly into place as expected. Include a javascript function to undo any ctrl+/- activity the user may do.

将主体宽度设置为静态 50vh,并且没有任何浮动或脱离父 div。并且仅使用表格进行样式化,因此所有内容都按预期严格固定到位。包括一个 javascript 函数来撤消用户可能执行的任何 ctrl+/- 活动。

Everybody will hate you except the people who tell you to make things match their mock-up, and they will be ecstatic. And everyone knows their opinion is the only one that matters.

每个人都会讨厌你,除了那些告诉你让东西与他们的模型相匹配的人,他们会欣喜若狂。每个人都知道他们的意见是唯一重要的。

回答by DA.

Yes. Or, rather, no.

是的。或者,更确切地说,没有。

Er, I mean, it doesn't matter. Use the one that makes sense for your particular project. PX and EM or both equally valid but will behave a bit different depending on your overall page's CSS architecture.

呃,我的意思是,没关系。使用对您的特定项目有意义的那个。PX 和 EM 或两者同样有效,但根据您整个页面的 CSS 架构,其行为会有所不同。

UPDATE:

更新:

To clarify, I'm stating that usually it likely doesn't matter which you use. At times, you may specifically want to choose one over the other. EMs are nice if you can start from scratch and want to use a base font size and make everything relative to that.

为了澄清起见,我是说通常您使用哪个并不重要。有时,您可能特别想选择其中之一。如果您可以从头开始并希望使用基本字体大小并制作与此相关的所有内容,那么 EM 会很好。

PXs are often needed when you're retrofitting a redesign onto an existing code base and need the specificity of px to prevent bad nesting issues.

当您在现有代码库上重新设计并需要 px 的特殊性以防止错误的嵌套问题时,通常需要 PX。