在图像尺寸上使用 rem、em 和 px

新手上路,请多包涵

我正在寻找有关这些单位在图像尺寸上的使用的一些解释,但找不到任何解释。我在一些地方读到忘记像素并只使用 rem/em,但我不知道它是否也适用于图像尺寸(宽度/高度)。

例如,在下面的这种情况下我应该使用哪一个?

 <img src="https://i.imgur.com/NReN4xE.png" style="width: 5rem;" />5rem<br>
<img src="https://i.imgur.com/NReN4xE.png" style="width: 5em;" />5em<br>
<img src="https://i.imgur.com/NReN4xE.png" style="width: 100px;" />100px<br>

原文由 Luiz 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 392
2 个回答
  • px 渲染像素值
  • rem uses the root element ( html ) using its font-size as the base (16px by default) to calculate its size, so basically your rem 来自 img 的值乘以 font-sizehtml
  • em uses the first parent with a font-size to calculate the size it needs to render (calculated the same as rem above - parent computed px 值乘以你的 em )。如果那个父母在其 font-size 中使用 em ,孩子将使用计算/计算的 font-size

解释可能很难理解(尤其是 em ),看看这里: https ://jsfiddle.net/6ydf931w/

在大多数情况下,我倾向于避免对几乎所有内容使用 em ,因为如果您不永久知道它的使用位置,它可能会导致意外结果。

我通常将 rem 限制为文本,以防需要全局更改。

px 非常可预测,如果这对你有用,使用它没有坏处。

原文由 NickZA 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果您想要一个响应式网站,最好使用 rem 而不是像素。这是因为像素是绝对单位,而 rem 是相对于根字体大小的单位。

想象一下,您的所有元素都以像素为单位,并且希望在窗口较小时缩放所有元素。如果你有像素,你将不得不一一更改所有内容。然而,使用 rem 你可以改变你的根的字体大小,所有的东西都会立即缩放。

尝试更改下面示例中的字体大小并自行查看:

 html{
      font-size: 30px;
    }

.pixel1{
      width: 30px;
      height: 30px;
      background-color: red;
      margin-bottom: 10px;
}

.pixel2{
      width: 40px;
      height: 40px;
      background-color: red;
      margin-bottom: 10px;
}

.rem1{
      width: 1rem;
      height: 1rem;
      background-color: blue;
      margin-bottom: 10px;
}

.rem2{
      width: 1.4rem;
      height: 1.4rem;
      background-color: blue;
}
 <div class="pixel1"></div>
<div class="pixel2"></div>
<div class="rem1"></div>
<div class="rem2"></div>

原文由 Vasilis Georgoudis 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏