我想知道人们对完全基于 EM 有何看法?就我个人而言,我几乎完全赞同它,字体大小、布局、媒体查询等等。与用户的个人偏好相关是非常有意义的。
但是,当涉及到 javascript 时,似乎很难使用像素以外的任何东西。
例如,如果我想在屏幕尺寸大于特定尺寸时添加图像,我可能会在 HTML 中这样做:
if (document.documentElement.clientWidth > 500) {
document.write('<img src="whatever.jpg" alt="whatever" />');
}
或者,在 JS 中,当屏幕到达媒体查询断点时,我可能想要更改某些内容(也许交换一个元素)。然而,我最终会在 CSS 中混合使用 EM,在 JS 中混合使用像素,如果用户的字体大小不是默认大小,它们将不匹配。
这有意义吗?有人有什么建议吗?也许 EM 字体和 px 用于布局?但这失去了 EM 的一些优点。
最佳答案
用px就可以了。您可以轻松计算 px-em。我建议阅读 this exhaustive article来自 CSS-Tricks 关于您的问题
The most popular method in working with em values is to set the font-size on the body to 62.5%. Because the default browser font-size is 16px, this makes it 10px (without hard-setting it to 10px, which wouldn't cascade). Using 10 as a multiplier is much easier than using 16. This way, you need a font size of 18px? Use font-size: 1.8em.
So why bother with all this em business when it's just an abstraction of using pixel values anyway? Three possible reasons:
- The ARE resizeable in IE 6
- The relationship to other sizes (elastic width sites)
- Em's cascade like a mo-fo
The first one is the big one. If you basically want to use pixels but don't like the accessibility problems, em's may be the ticket for you.
关于JavaScript 和 EM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20306884/