为什么5rem可以装10个字符?

Why can 5rem hold 10 characters?

我一直在玩弄单字体(因为每个字符都和下一个一样宽)来匹配输入字段的长度。

为什么5rem等于10个字符?在 Chrome 和 Firefox 中进入我的输入字段?您会期望 10 个字符的宽度为 10rem:

input[type="text"] {
  border: 0;
  outline: 0;
  background: transparent;
  border-bottom: 2px solid black;
  font-family: 'monospace';
  overflow: hidden;
  width: 5rem;
}
<body id="body">
  <form onSubmit="return false">
    <input type="text" placeholder="your name" maxlength="10" required />
    <input type="submit" />
  </form>
</body>

http://codepen.io/alfredwesterveld/pen/RrypPv

rem单位与字宽无关

em 属性 对应于字体的高度 - 而不是宽度。

使用 ch 单位而不是 emrem 可能会有更好的运气;但是,ch 可能因浏览器而异 (http://codepen.io/stffn/pen/BNGVRN)

来源:

https://www.w3.org/TR/CSS2/fonts.html#font-size-props

Specify width in *characters*

How is font size calculated?

您要找的单位是ch:这个单位表示当前字体中字符'0'的宽度。在等宽字体中,1ch 相当于所有字符的宽度。

input {
  border: 0;
  outline: 0;
  background: transparent;
  border-bottom: 2px solid black;
  font-family: monospace;
  width: 9ch;
}
<input type="text" placeholder="your name" maxlength="10" required />

为了回答您的问题,单幅字符的高度通常是其宽度的两倍。所以 1ch ≈ 0.5em5em ≈ 10ch.