Search code examples
cssfontswidthmonospace

Use CSS to set the monospace font size based on the width of each character


Is there a way to use the width of the glyphs from a mono-spaced font to set the font size using CSS?

For example, I want the 10 characters inside this box to each be exactly 20px wide such that the text exactly fills the box, regardless of which monospace font is actually used. Currently the font-size directive that I'm using sets the height of the font, not the width of each letter.

#xyzzy {
  width: 200px;
  padding: 0;
  margin: 10px;
  border: 10px solid black;
  font-family: monospace;
  font-size: 20px;
}
<div id=xyzzy>1234567890</div>

The reason that I'm looking for this is that I have some content to show on mobile in a monospace font that can't wrap or extend off the screen. I'd like to be able to show exactly 44 characters of text across a 320px screen. I can't seem to get the font sized correctly such that it looks good in all browsers. It either extends past the viewport or leaves white space to the right.


Solution

  • Here is a JavaScript solution that starts out with 20px font size but then scales it proportionally to exactly fit into the desired 200px width.

    var xyzzy = document.getElementById('xyzzy');
    var currentWidth = xyzzy.clientWidth+1;
    var desiredWidth = 200;
    var currentFontSize = 20;
    xyzzy.style.fontSize = currentFontSize * desiredWidth / currentWidth + "px";
    #xyzzy {
      display: inline-block;
      white-space: nowrap;
      padding: 0;
      margin: 10px;
      border: 10px solid black;
      font-family: monospace;
      font-size: 20px;
    }
    <div id=xyzzy>1234567890</div>

    I used code from Calculate text width with Javascript to figure out the current text width.