【问题标题】:Unwanted early wrapping with "word-break: break-all" (and "break-word")使用“word-break: break-all”(和“break-word”)进行不需要的早期包装
【发布时间】:2022-02-10 23:33:22
【问题描述】:

我有一个长字符串,没有空格,我想把它放在一个 div 中,这样

  1. 尽可能地填满 div,不会溢出。
  2. 它在每一行使用相同数量的字符(最后一行除外,哪一行可能更少)。

div 是响应式 div,宽度为90vw,高度为84vh

HTML 是:

<div class = "content"><p><code>Some-very-large-string-without-white-space"</code></p></div>

使用一点 JavaScript 即可轻松缩放字体以使其适合:

function font_fiddle (selection) {
    let element  = document . querySelector (selection)

    let fontSize = element . clientHeight

    if (!element . innerHTML . length) {
        return;
    }

    element . style . fontSize = fontSize + 'px';
    while (element . scrollHeight > element . clientHeight && fontSize > 0) {
        element . style . fontSize  = -- fontSize + 'px';
    }
}

font_fiddle (".content") 在文档加载和窗口调整大小时被调用。这部分效果很好。

code 元素的 CSS 是:

code {
    word-break: break-all;
    color: lightgreen;
    background: black;
    font-style: initial;
    font-family: 'Source Code Pro', monospace;
    font-size: 95%;
}

由于等宽字体和word-break: break-all,我希望所有行(最后一行除外)具有相同数量的字符,并且具有直的右“边缘”。如果字符串只包含字母和数字,就会出现这种情况。但是我的字符串没有,这导致某些行比可能的短一个或几个字符:

将 CSS 更改为 word-break: break-word; 有一些效果,但我们的右边缘仍然是锯齿状的:

有没有办法让每一行都包含相同数量的字符,而不管这些字符是什么?

这一切都在 MacOS 上使用 Firefox。

【问题讨论】:

    标签: javascript html css word-break


    【解决方案1】:

    使用

      text-align: justify;
      text-justify: inter-character;
      word-break: break-all;
    

    我想它会解决你的问题。

    div {
      width: 50vw;
      height: 50vh;
      border: 1px solid;
      margin: auto;
      
      
      text-align: justify;
      text-justify: inter-character;
      word-break: break-all;
      
      
      background: #000;
      color: green;
    }
    <div class="container">
     Inmyyo/unger5andmorevu5l*nerableyearsmyfathe*rgave45me/5someadvicethatI'vebeentur45ningo/ver/i5n24ymindeversince.5'W4heneve*ryou-/55feel-55lik8ec5*rit4icizi5ng45anyo4ne5'h*etol4/545dme,'j4u/s5trememberthatallthepeoplei5n45th4sworld5haven't/hadt5h4eadvanta5gesthatyou'vehad.'
    </div>

    【讨论】:

    • 它确实使右边距是合理的。但它并不能解决单词中断问题——我们的行仍然会比其他行包含更少的字符。
    【解决方案2】:

    你可以尝试使用overflow-wrap:anywhere;

    【讨论】:

    • overflow-wrap: anywhereword-break: break-word 给出相同的结果。
    猜你喜欢
    • 2016-05-17
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    相关资源
    最近更新 更多