2

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.

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
  • No, there is no setting to make font glyphs proportional to their element's width. you would need javascript. - http://stackoverflow.com/questions/8639249/how-to-resize-font-size-proportionally-to-div-size – Paulie_D Mar 18 '15 at 15:01
  • I'm open to using JavaScript. Its not as clean as pure CSS would be. I would prefer a CSS solution, but I would accept a solution with JS. – Stephen Ostermiller Mar 18 '15 at 15:04

1 Answers1

-1

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.

Community
  • 1
  • 1
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109