如何设置<div>的宽度以适应等宽字体中的常量字母数?

btw*_*tw0 13 html javascript css

我研究了一段时间,一直没有找到解决CSS还,emex单位未在这种情况下是正确的.我想要的只是一个完全适合80x25等宽文本的div框.我是否必须使用Javascript解决方案?

sun*_*aku 26

尝试使用CSS3规范中ch描述的单元:

等于用于渲染它的字体中找到的"0"(ZERO,U + 0030)字形的已用预先测量值.

因此width: 80ch指定了80个字符的宽度限制.


Bli*_*ixt 5

em如果您知道字体所涉及的正确比率,​​则在这种情况下有效.请尝试以下HTML:

(这样做的危险在于某些浏览器会调整字体,这可能会改变字体的宽度/高度.对于100%的准确度,您可能需要使用JavaScript.)

<style type="text/css">
    #text-container {
        border: #f00 solid 1px;
        font: 10px/1.2 Courier, monospace;
        width: 48em;  /* 80 x 0.6 (the width/height ratio of Courier) */
        height: 30em; /* 25 x 1.2 (line-height is 1.2) */
        overflow: hidden;
    }
</style>

<div id="text-container">
00000000001111111111222222222233333333334444444444555555555566666666667777777777
12345678901234567890123456789012345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890123456789012345678901234567890
</div>
Run Code Online (Sandbox Code Playgroud)