Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

css - Specify width in *characters*

When using a fixed width font, I'd like to specify the width of an HTML element in characters.

The "em" unit is supposed to be the width of the M character, so I should be able to use it to specify a width. This is an example:

<html>
  <head>
    <style>
      div {
        font-family: Courier;
        width: 10em;
      }
    </style>
  </head>
  <body>
    <div>
      1 3 5 7 9 1 3 5 7 9 1
    </div>
  </body>
</html>

The result is not what I wanted as the browser line breaks after column 15, not 10:

1 3 5 7 9 1 3 5
7 9 1

(Result in Firefox and Chromium, both in Ubuntu.)

Wikipedia's article says that an "em" is not always the width of an M, so it definitely looks like the "em" unit can't be trusted for this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

ch unit

The unit you're looking for is ch. According to the MDN docs:

ch: Represents the width, or more precisely the advance measure, of the glyph "0" (zero, the Unicode character U+0030) in the element's font.

It is supported in current versions of major browsers (caniuse).

Example

pre {
    width: 80ch; /* classic terminal width for code sections */
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...