em 中的媒体查询不受基本字体大小的影响
Media queries in em not affected by the base font size
我想了解为什么设置不同的基本字体大小不会影响媒体查询的 EM 值。
它们作为默认基本字体大小为 16px,而其余内容反应正常。
亲自尝试一下:
PX 中的媒体查询:
https://jsfiddle.net/sebtp/n8x0tuvq/5/[确定]
EM 中的媒体查询:
https://jsfiddle.net/sebtp/n8x0tuvq/7/[不正常]
REM 中的媒体查询:
https://jsfiddle.net/sebtp/n8x0tuvq/10/[不正常]
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;
}
要获得与 html
规则中定义的字体大小相关的字体大小,您必须使用 rem 单位,而不是 em
. em
相对于元素本身,如果没有字体大小定义,相对于具有字体大小定义的 parent/next 祖先(也可以在浏览器默认设置中定义,顺便说一句).
OP 评论后添加:
有趣:由于您以百分比定义 html
字体大小,显然浏览器继续将其内部默认设置视为根大小(它从中派生出 rem 单位)。如果将 html
规则中的字体设置更改为 px
设置,rem
单元将相应地响应 字体大小 ,但是浏览器仍然使用其默认字体大小 (16px) 水平测量(至少在 Firefox 中)。看这里(看 12px 设置和 CSS 规则中的注释):https://jsfiddle.net/zwc00gtk/2/
再加一个:
对于"regular"水平测量,rem单位按预期工作,在下面的例子中,浅绿色背景的.wrap
div设置为width: 40rem
,当html
中的font--size设置为12px
时计算为480px,当html
中的font-size为62.5%
时甚至变为400px(=10px )
https://jsfiddle.net/n2dww2mt/1/
所以只有媒体查询不接受除 16px 以外的任何其他单位作为 rem
单位...
我想了解为什么设置不同的基本字体大小不会影响媒体查询的 EM 值。
它们作为默认基本字体大小为 16px,而其余内容反应正常。
亲自尝试一下:
PX 中的媒体查询: https://jsfiddle.net/sebtp/n8x0tuvq/5/[确定]
EM 中的媒体查询: https://jsfiddle.net/sebtp/n8x0tuvq/7/[不正常]
REM 中的媒体查询: https://jsfiddle.net/sebtp/n8x0tuvq/10/[不正常]
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;
}
要获得与 html
规则中定义的字体大小相关的字体大小,您必须使用 rem 单位,而不是 em
. em
相对于元素本身,如果没有字体大小定义,相对于具有字体大小定义的 parent/next 祖先(也可以在浏览器默认设置中定义,顺便说一句).
OP 评论后添加:
有趣:由于您以百分比定义 html
字体大小,显然浏览器继续将其内部默认设置视为根大小(它从中派生出 rem 单位)。如果将 html
规则中的字体设置更改为 px
设置,rem
单元将相应地响应 字体大小 ,但是浏览器仍然使用其默认字体大小 (16px) 水平测量(至少在 Firefox 中)。看这里(看 12px 设置和 CSS 规则中的注释):https://jsfiddle.net/zwc00gtk/2/
再加一个:
对于"regular"水平测量,rem单位按预期工作,在下面的例子中,浅绿色背景的.wrap
div设置为width: 40rem
,当html
中的font--size设置为12px
时计算为480px,当html
中的font-size为62.5%
时甚至变为400px(=10px )
https://jsfiddle.net/n2dww2mt/1/
所以只有媒体查询不接受除 16px 以外的任何其他单位作为 rem
单位...