6

I have been playing around with monofonts (because every character as wide as the next) to match length of input field.

How come 5rem is equal to 10 characters? into my input field in both Chrome and Firefox? You would expect 10 characters to have width 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

TylerH
  • 20,799
  • 66
  • 75
  • 101
Alfred
  • 60,935
  • 33
  • 147
  • 186

2 Answers2

8

The unit you are looking for is ch: This unit represents the width of the character '0' in the current font. In a monospace font, 1ch is equivalent of all character width.

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 />

To answer your question, monopsace characters have often a height two times bigger than their width. So 1ch ≈ 0.5em and 5em ≈ 10ch.

tzi
  • 8,719
  • 2
  • 25
  • 45
  • What does browser support for ch look like? I've never seen this before. – tayvano Jan 28 '16 at 01:13
  • 2
    @Taylor The browser support of the `ch`unit is Chrome 27+, Firefox 1+, IE9+, Safari 7+ – tzi Jan 28 '16 at 01:18
  • But this only works for monospace fonts? Also possible for all fonts only with css? – Alfred Jan 28 '16 at 11:29
  • 1
    The unit is the width of the character '0' for every font, even non-monospace ones. As far as I know, it's near to `0.5em` most of the time. – tzi Jan 29 '16 at 12:31
5

The rem unit does not relate to the width of a character.

The em property corresponds to the height of the font - not the width.

You might have better luck using the ch unit instead of em or rem; however, ch can differ from browser to browser (http://codepen.io/stffn/pen/BNGVRN)

Sources:

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

Specify width in *characters*

How is font size calculated?

Community
  • 1
  • 1
Andrew Hendrie
  • 6,205
  • 4
  • 40
  • 71