【问题标题】:Vertically align html-entity characters in monospace font?垂直对齐等宽字体中的html实体字符?
【发布时间】:2019-10-05 11:06:15
【问题描述】:

有时,我需要在字符列垂直对齐的地方键入文本,最简单的方法当然是使用 font-family "monospace"、"Courier" 等。

不过,我注意到的是,许多 html 实体代码字符(表情符号等)并不总是符合这个固定的字体宽度, 但仍会比普通字符更宽,并且将同一行上的后续字符“推”到右侧,尽管使用了等宽字符。

例如:

♡ = ♡ --- 在等宽中稍宽。

♛ = ♛ --- 在等宽中太宽了。

♥ = ♥ --- 这遵循我的 Windows 笔记本电脑上的等宽宽度,但在使用 android/chrome 查看时太宽了。

是否有任何可用的修复/解决方法来防止这种异常行为?

我在想,如果有办法“压缩”这些字符的宽度,以确保它们都与固定的字符宽度对齐,并且最好在不同的设备上统一工作?

或者其他可行的方案?

【问题讨论】:

    标签: html css html-entities monospace


    【解决方案1】:

    我相信这是因为您的等宽字体(例如 Courier)没有那些 unicode 字形。然后系统将使用备用字体来呈现表情符号,并且该字体不是等宽的。

    因此,最好的解决方案是使用支持您要使用的表情符号的等宽字体。

    您也可以put in a span around those characters and force the width

    .monospace {
      font-family: monospace;
      font-size: 20px;
    }
    .monospace > span {
      display: inline-block;
      width: 12px;
    }
    <div class="monospace">
      foo<br>
      <span>♡</span><span>♛</span><span>♥</span>
    </div>

    (请注意,如果您的编辑器设置正确,您可以直接在源代码中使用 unicode 字符。)

    【讨论】:

      【解决方案2】:

      [编辑] 我编辑了我的答案,以使字母间距相等,而不必根据我之前的答案添加跨度标签或在每个段落上使用一个类。现在,只需键入段落,字母就会对齐。

      这将对齐列中任何字体的字母,但是我使用等宽,因为这是您有兴趣使用的。

      注意,我在示例中添加了一个边框来显示对齐,只需删除此样式即可。

      运行代码sn -p查看。

      window.onload = function() {
          numRows = document.getElementById("spacingcontainer").children;
          for (i=0; i<numRows.length; i++) {
              temp = "";
              for (j=0; j<numRows[i].innerHTML.length; j++) {
                  letter = numRows[i].innerHTML[j];
                  temp += "<span>" + letter + "</span>";
              }
              numRows[i].innerHTML = temp;
          }
      }
      	#spacingcontainer {
      	    display:table;
      	    font:18px monospace;
      	}
      	#spacingcontainer p {
      	    display:table-row;
      	}
      	#spacingcontainer p span {
      	    display:table-cell;
      	    width:12px;
      	    text-align:center;
      	    border:1px solid silver; /* remove border */
      	}
      <div id="spacingcontainer">
      <p>Align letters in columns.</p>
      <p>&#9825;a&#9819;&hearts; &#174;q f&#174; h&#8364;j&#9825;i&#165; &hearts;&#163;&#162;&#9820;&#9826;&#9825;&hearts;</p>
      <p>This is monospaced font</p>
      </div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-30
        • 2016-01-21
        • 2011-11-24
        • 1970-01-01
        • 1970-01-01
        • 2014-07-24
        • 1970-01-01
        相关资源
        最近更新 更多