Make CSS media query use the em size of the html document rather than the browser?

烂漫一生 提交于 2019-12-01 03:58:36

No, you cannot, because in a media query, “Relative units in media queries are based on the initial value, which means that units are never based on results of declarations. For example, in HTML, the ‘em’ unit is relative to the initial value of ‘font-size’.” (Media Query spec, clause 6 Units). The initial value of font-size is medium, which is mapped to a physical size in a browser-dependent manner (independently of anything that you can set in CSS).

The conclusions depend on how you set the font size. If you are setting the font size of the root element in pixels, it is logical to use pixels in media queries, too, since the use of em would not provide any flexibility. If you set the root element’s font size as a percentage, it makes sense to use em in media queries, but you just need to take into account that em means the browser’s default font size there and you need to select the multiplier of em accordingly.

From W3C (http://www.w3.org/TR/CSS21/syndata.html)
The 'em' unit is equal to the computed value of the 'font-size' property of the element on which it is used. The exception is when 'em' occurs in the value of the 'font-size' property itself, in which case it refers to the font size of the parent element.

html { font-size:1em; width:42em; }
body { font-size:1.6em; }

@media screen and (max-width:40em) {
    div#page { font-size:0.875em; } /* 14px font */
}

Note: 42em will probably never be 100% of the browser window's width. If you change the @media to act differently for different screen widths (max-width:1200px), (max-width:1024px) you'll probably get more of the effect I think you're after.

I've just been looking in to the same thing, and AFAIK there is no way to alter the "native" font-size of the browser/device; but this is actually good if you look at it a certain way.

The media-query and the html tag --if set in relative units-- are referring to the same base number on any given device or browser (in the case of desktop browsers it is 16px, but can be different on other devices or if user changes their zoom).

So if you set your html text-size in a percentage or em-measure of this value (for the desktop equivalent of 12px, use 75% or 0.75em), and then set your media queries based on dividing the pixel width by this value (for the desktop equivalent of 960px, use 60em), everything should fall in to place on every device at every zoom level.

See also this link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!