【问题标题】:Same REM measurement results in different pixel values相同的 REM 测量会导致不同的像素值
【发布时间】:2020-10-28 00:53:35
【问题描述】:

我正在使用 REM 值。在较小的屏幕尺寸下,我的基本字体大小相当于 9 像素:

html {
    font-size: 56.25%;
}

(16px x 56.25% = 9px)

我注意到 Chrome 会根据所测量的内容以不同的方式计算像素值。例如:

我有一个<header> 元素。其高度由 line-height 决定:6.3rem (6.3 x 9px = 56.7px)。

header { line-height: 6.3rem }

Chrome 将其计算为 57 像素。

但是,如果我将代码更改为

header { height: 6.3rem; }

Chrome 将其计算为 57.69 像素。

如果我有一个绝对位于标题下方的导航:

nav { position: absolute; top: 6.3rem; }

Chrome 计算顶部距离为 56.7px

这些差异证明是一种痛苦,因为标题和导航具有不同的背景颜色和边框,而 Chrome 正在忍受这些亚像素差异。

为什么浏览器会以不同的方式呈现相同的测量值?

JSFiddle 这里: https://jsfiddle.net/79tbdovq/1/

在 Chrome 中显示了一个不应该显示的子像素边框底部。尽管出于某种原因在 JSFiddle 中它工作正常。

【问题讨论】:

  • 您尝试添加box-size:border 吗?
  • 这不是问题。问题是相同的 rem 值会导致不同的像素测量值。
  • 原因是亚像素舍入。因此,px 单位通常优于 rem 或 em。

标签: html css


【解决方案1】:

line-height 的行为很诡异... (similar subject)

你的计算很好,但即使你写了line-height: 56.7px;,它也会在 Chrome 工具中显示line-height: 56px

无论如何,如果您想解决使用高度和框边框的问题:

header {
  height: 6.3rem;              /* ADDED */
  line-height: 6.3rem;
  border-bottom: 1px solid black;
  font-size: 2rem;
  box-sizing: border-box;     /* ADDED */
}

演示

html, body {
    font-size: 56.25%;
}
body{
  margin: 0;
}

header {
  height: 6.3rem;             /* ADDED */
  line-height: 6.3rem;
  border-bottom: 1px solid black;
  font-size: 2rem;
  box-sizing: border-box;     /* ADDED */
}

nav {
  position: absolute;
  top: 6.3rem;
  left: 0;
  right: 0;
  background-color: yellow;
  font-size: 2rem;
}
<header>Logo and hamburger</header>
<nav>Nav list</nav>

【讨论】:

  • 这并不能解释为什么三个(行高、高度和绝对)完全相同的测量值会导致三个不同的像素测量值。
  • 你读过我提出的类似主题吗?我不打算复制/粘贴主要答案的大量说明
  • 不仅 line-height 给出不同的结果,而且 position:absolute 给出了不同的高度结果。我还没有测试过,但这是否意味着 REM 中的填充、边距和其他测量会导致不同的像素测量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-11
  • 2011-05-26
相关资源
最近更新 更多