响应式图像如何与以 `sizes` 长度提供的 `em` 一起工作?

How do responsive images work with `em` supplied as a length in `sizes`?

在响应式图像中使用时,浏览器如何理解 em 单位?

<img alt="A giraffe" src="giraffe.jpg"
     srcset="giraffe@1.5x.jpg 600w, giraffe@2x.jpg 800w, [etc.]"
     sizes="(max-width: 40em) 40em">

这已通过验证,但我没有在浏览器控制台中看到警告。但是如果图像预加载器的全部目的是在 下载和解析 CSS 之前获取图像,那么浏览器对 em 使用什么?

是否只是它的默认 font-size 适用于 <html>?为了清楚起见,我应该使用 rem 吗?用户缩放时两者有区别吗?

这不是理论上的;当然,我 using em in my media query breakpoints, and some images are constrained by a container sized for optimal line length (using em

我查看了规范,但它对新的响应式图像功能非常简洁。

5.1.1. Font-relative lengths: the ‘em’, ‘ex’, ‘ch’, ‘rem’ units

Aside from ‘rem’ (which refers to the font-size of the root element), the font-relative lengths refer to the font metrics of the element on which they are used. The exception is when they occur in the value of the ‘font-size’ property itself, in which case they refer to the computed font metrics of the parent element (or the computed font metrics corresponding to the initial values of the ‘font’ property, if the element has no parent).

em unit

Equal to the computed value of the ‘font-size’ property of the element on which it is used.
http://www.w3.org/TR/css3-values/#font-relative-lengths

em css 单位等于当前元素的字体大小。 font-size 属性 是继承的。因此,元素(在本例中为 img)的大小将根据 font-size 属性 的 40 倍调整。如果用户缩放页面(增加字体大小),em 单元自动更新为 font-size 属性。

基本字体大小将由浏览器决定,如果浏览器是 运行 on windows on mac 并且用户没有更改字体大小则基本字体大小将是 16px(通常)。在 Linux、BSD 或任何其他系统上,字体大小将由桌面环境设置并且可能会有所不同。

因此,虽然保守地您可以假设字体大小为 16px,但在很多情况下您是错误的。

我让官方 W3C #respimg 聊天室里的人耳目一新,this is what they had to say:

<Tigt> Pardon me folks, I had a question about how em is interpreted when used inside sizes
<TabAtkins> Tigt: Same as in Media Queries - they're relative to the initial font size.
<TabAtkins> (Not the font size on <html>, the initial font size, as set by the user's personal settings.)


<Wilto> 16px almost everywhere, so long as you haven’t changed the font-size of html.
<TabAtkins> Tigt: rem is treated identical to em here.

所以速读是:

  • sizes 或媒体查询中使用时,emrem 都指定表示“用户的默认值 font-size
  • 控制图像在页面上布局方式的实际 emrem 如果您 CSS 更改它
  • ,最终可能会有所不同
  • 这意味着如果他们想给图像预加载器提供真实信息,则 更改 em 的默认大小

W3C Media Queries:

This media query expresses that style sheet is usable on screen and handheld devices if the width of the viewport is greater than 20em.

 @media handheld and (min-width: 20em), screen and (min-width: 20em) { … }

The ‘em’ value is relative to the initial value of ‘font-size’.