仅在必要时显示连字符? (软连字符不会切断它)
P粉225961749
P粉225961749 2023-08-25 11:10:51
[CSS3讨论组]

是否可以在 CSS 中使用连字符或软连字符,这样就不会不必要地渲染连字符?

我的目标是尽可能保留原始文本并打破任何单词,除非绝对关键,因为它们太长而无法适应容器宽度。

我的具体案例

我想以这样的方式渲染文本“Hi Superman”:

如果“Superman”这个词太长而无法放入容器中,我想以某种方式将其连字符,例如:

Hi Super-
man

但是,如果“Superman”这个词可以放入容器中,则必须在不使用连字符的情况下呈现它

Hi
Superman

如果上述情况是可能的(“Superman”可以不加连字符),则添加不必要的连字符是不可接受的:

Hi Super-
man

我可以根据需要更改 HTML。我可以以有意义的方式插入连字符(只要每个连字符之间超过 3 个字母就可以。“Superma-n”永远不会好)

我尝试过的

我认为软连字符是解决方案。所以我用了:Hi Super­man

但我发现这会导致上面显示的“不必要的连字符”的不可接受的情况。

显示失败的代码片段:

body { 
  margin-left: 30px;
}
div {
   border: solid 1px black;
}
.wide {
  border: solid 1px blue;
      width: 500px;
}
.narrow { 
  border: solid 1px red;
  width: 360px;
}
 h2 {
   font-family: 'Courier New';
    font-weight: 400;
    font-size: 87px;
  }
code {
 background-color: #eee;
}
<p> <code>Super&amp;shy;man</code> looks good in really narrow containers where the full word "Superman" would not fit</p>
<p>
<div class="narrow"><h2>Hi Super&shy;man</h2></div>

<p>But in this case the word "Superman" would fit unhypenhated on the second row. But the damn CSS decides to add hyphens anyway. Unacceptable in my case!
Again, this uses the same code as the previous example
<code>Super&amp;shy;man</code></p>
<div class="wide"><h2>Hi Super&shy;man</h2></div>

<p>I even tried adding a wordbreak tag before "Superman", like this <code>Hi &lt;wbr&gt; Super&amp;shy;man</code> but it does not help</p>
<p>  </p>
<div class="wide"><h2>Hi <wbr>Super&shy;man</h2></div>

我可以仅使用 CSS 来解决上面的示例吗? (尝试了不同的word-break属性,但没有成功)

我的猜测是,由于 CSS 的性质,仅使用简单的 HTML 和 CSS 是不可能解决这个问题的。我假设 CSS 只是逐行解析文本,它永远无法知道某个单词是否“更适合”下一行文本。如果找到连字符,它将尝试在当前文本行中容纳最大数量的字符。

我想仅使用 HTML 和 CSS 来解决这个问题,或者根本不使用。

最好是:

  • 不使用 JavaScript 进行文本解析。

  • 我不想根据 div 的宽度以及我认为文本是否需要连字符来为每个 div 设置不同的 CSS 属性。

  • 不想在我的文字周围添加包装

  • 没有自动连字符会导致可笑的连字符,例如“Superma-n”(但是在紧要关头,只要每个连字符之间有 3 个字符,我就可以使用自动连字符。例如“Sup-erman” ”)

P粉225961749
P粉225961749

全部回复(1)
P粉950128819

在长单词周围使用带有 display: inline-block 的容器。

body { 
  margin-left: 30px;
}
div {
   border: solid 1px black;
}
.wide {
  border: solid 1px blue;
      width: 500px;
}
.narrow { 
  border: solid 1px red;
  width: 360px;
}
 h2 {
   font-family: 'Courier New';
    font-weight: 400;
    font-size: 87px;
  }
code {
 background-color: #eee;
}

.unbreakable {display:inline-block}
<p> <code>Super&amp;shy;man</code> looks good in really narrow containers where the full word "Superman" would not fit</p>
<p>
<div class="narrow"><h2>Hi <span class="unbreakable">Super&shy;man</span></h2></div>

<p>And in this case the word "Superman" would fit unhypenhated on the second row.<br/>
This uses the same code as the previous example</p>
<div class="wide"><h2>Hi <span class="unbreakable">Super&shy;man</span></h2></div>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号