【问题标题】:5rem can hold 10 characters how come?5rem 可以容纳 10 个字符怎么来的?
【发布时间】:2016-05-05 05:00:36
【问题描述】:

我一直在玩单字体(因为每个字符都与下一个字符一样宽)以匹配输入字段的长度。我的问题是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

【问题讨论】:

  • 作为旁注,rem 单位是相对于您的 sn-p 未指定的“基本字体大小”(html 标签的)。浏览器默认为 16 像素。

标签: css html em


【解决方案1】:

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

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

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

【讨论】:

  • 浏览器对 ch 的支持是什么样的?我以前从未见过这种情况。
  • @Taylor chunit 的浏览器支持 Chrome 27+, Firefox 1+, IE9+, Safari 7+
  • 但这仅适用于等宽字体?也可以只使用 css 的所有字体?
  • 单位是每个字体的字符'0'的宽度,即使是非等宽字体。据我所知,大部分时间都在0.5em附近。
【解决方案2】:

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?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-27
    • 2013-04-06
    • 1970-01-01
    • 2016-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多