怎么来5rem可以容纳10个字符?

时间:2016-01-28 00:48:43

标签: css html5 em

我一直在玩单字形(因为每个字符都与下一个字符一样宽)以匹配输入字段的长度。我的问题是如何将5rem is equal to 10 characters?放入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

2 个答案:

答案 0 :(得分:5)

您要查找的单位是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 />

要回答您的问题,monopsace字符的高度往往是宽度的两倍。所以1ch ≈ 0.5em5em ≈ 10ch

答案 1 :(得分:3)

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?