JavaScript 和 EM

标签 javascript css

我想知道人们对完全基于 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:

  1. The ARE resizeable in IE 6
  2. The relationship to other sizes (elastic width sites)
  3. 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/

相关文章:

javascript - 绘图轴标题上的工具提示

javascript - 将 fontawesome 图标设置为占位符

javascript - 如何在使用 axios 和 ReactJS 使用react选择后获取数据?

css - 如何为一系列字体粗细设置@font-face

html - 无法对齐标签,在表单中输入

javascript - JS 将内联 css 添加到 html

javascript - 防止 firefox 在溢出元素更改时重置滚动位置

html - 可调整的 div 和定位

html - img 上的最大宽度可防止图像缩小

javascript - CSS jQuery - 在我的 slider 中使用元素符号作为指示器