我正在寻找有关这些单位在图像尺寸上的使用的一些解释,但找不到任何解释。我在一些地方读到忘记像素并只使用 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 许可协议
px
渲染像素值rem
uses the root element (html
) using itsfont-size
as the base (16px by default) to calculate its size, so basically yourrem
来自img
的值乘以font-size
在html
em
uses the first parent with afont-size
to calculate the size it needs to render (calculated the same asrem
above - parent computedpx
值乘以你的em
)。如果那个父母在其font-size
中使用em
,孩子将使用计算/计算的font-size
解释可能很难理解(尤其是
em
),看看这里: https ://jsfiddle.net/6ydf931w/在大多数情况下,我倾向于避免对几乎所有内容使用
em
,因为如果您不永久知道它的使用位置,它可能会导致意外结果。我通常将
rem
限制为文本,以防需要全局更改。px
非常可预测,如果这对你有用,使用它没有坏处。