Media queries in em not affected by the base font size

余生颓废 提交于 2019-12-24 04:07:52

问题


I'm trying to understand why setting a different base font size doesn't affect the EM values for the media queries.

They are acting as the default base font size is 16px, while the rest of the content reacts normally.

Try it yourself:

Media queries in PX: https://jsfiddle.net/sebtp/n8x0tuvq/5/ [OK]

Media queries in EM: https://jsfiddle.net/sebtp/n8x0tuvq/7/ [NOT OK]

Media queries in REM: https://jsfiddle.net/sebtp/n8x0tuvq/10/ [NOT OK]

html {
    font-size: 62.5%; /*setting the base font size to 10px*/
}

body {
  background: white;
}
span { 
  font-size:6em; /* 60px, as it should */
}

@media only screen and (min-width: 30em) { /* 480px, should be 300px */
  body {
    background:red;
  }

 @media only screen and (min-width: 40em) { /* 640px should be 400px */
  body {
    background:cyan;
  }

  @media only screen and (min-width: 50em) { /* 800px should be 500px */
  body {
    background:yellow;
  }

回答1:


To get font sizes that are relative to the font-size defined in an html rule, you have to use rem units, not em. em is relative to the element itself, and if there is no font-size definition, to the parent/next ancestor which has a font-size definition (which could also be defined in the browsers default settings, BTW).

ADDITION AFTER COMMENT OF OP:

Interesting: Since you define the html font size in percent, obviously the browser continues to treat its internal default setting as the root size (from which it derives the rem unit). If you change the font-setting in the html rule to a px setting, rem units will respond accordingly concerning the font-size, but the browser still keeps using its default font size (16px) for horizontal measuring (at least in Firefox). Have a look here (watch the 12px setting and the comments in the CSS rules): https://jsfiddle.net/zwc00gtk/2/

ONE MORE ADDITION:

For "regular" horizontal measuring, the rem unit works as expected, in the following example the .wrap div with the light-green background is set to width: 40rem, which is calculated as 480px when the font--size in html is set to 12px, and even becomes 400px when font-size in htmlis 62.5% (= 10px)

https://jsfiddle.net/n2dww2mt/1/

So it's only the media queries that won't accept anything else than 16px as the rem unit...



来源:https://stackoverflow.com/questions/42903778/media-queries-in-em-not-affected-by-the-base-font-size

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