HTML – 如何防止文本溢出和被剪辑?

我需要在弹性框内使用斜体字体,但文本因溢出而被剪切.

我想要的文字条件:

>不得看到溢出
>不得剪裁文字

这是我目前的情况(小蓝框表示文本框大小):

《HTML – 如何防止文本溢出和被剪辑?》

我想要这个:

《HTML – 如何防止文本溢出和被剪辑?》

怎么能实现这一目标?

我从this SO post得到了一个黑客攻击,但是你可以在下面的片段中看到一个严重的问题.

我目前的代码在这里:

body {
  font-family: sans-serif;
  font-size: 30px;
}
.ellipsiswrap {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
.italic {
  font-style: italic;
}
.italicguard {
  padding-right: 0.3em;
  margin-right: -0.3em;
}
.usernamewrapper {
  font-size: 1.2em;
  overflow: hidden;
  display: flex;
  background-color: #303030;
  color: #fff;
}
.opacity5 {
  opacity: 0.5;
}
.screenname {
  margin-left: 0.3em;
  flex: 1;
}

.widthlimit150 {
  width: 300px;
}

.widthlimit70 {
  width: 140px;
}

.letterspacing {
  letter-spacing: .12em
}

.wordspacing {
  word-spacing: .12em
}
<p>Original:</p>

<div class="usernamewrapper">
  <span class="ellipsiswrap italic">username W</span>
  <span class="screenname ellipsiswrap opacity5 italic italicguard">@username</span>
</div>

<p>Hack:</p>

<div class="usernamewrapper italic italicguard">
  <span class="ellipsiswrap italicguard">username W</span>
  <span class="screenname ellipsiswrap opacity5 italicguard">@username</span>
</div>

<p>Behavior that must be kept:</p>

<div class="usernamewrapper italic widthlimit150">
  <span class="ellipsiswrap">username W</span>
  <span class="screenname ellipsiswrap opacity5">@username</span>
</div>

<div class="usernamewrapper italic widthlimit70">
  <span class="ellipsiswrap">username W</span>
  <span class="screenname ellipsiswrap opacity5">@username</span>
</div>

<p>Problem with the hack:</p>

<div class="usernamewrapper italic italicguard widthlimit70">
  <span class="ellipsiswrap italicguard">username W</span>
  <span class="screenname ellipsiswrap opacity5 italicguard">@username</span>
</div>

<p>letter-spacing from Michael_B:</p>

<div class="usernamewrapper">
  <span class="ellipsiswrap italic letterspacing">username W</span>
  <span class="screenname ellipsiswrap opacity5 italic italicguard">@username</span>
</div>

<p>word-spacing from Michael_B:</p>

<div class="usernamewrapper">
  <span class="ellipsiswrap italic wordspacing">username W</span>
  <span class="screenname ellipsiswrap opacity5 italic italicguard">@username</span>
</div>

最佳答案 尝试使用CSS letter-spacing属性.

它基本上在每个字母之前和之后添加填充.

.ellipsiswrap {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  letter-spacing: .12em; /* just enough to clear the last letter;
                            even .2em  doesn't look bad; */
}

我经常使用字母间距来提高可读性.在这种情况下,它可能有助于防止切断.

参考:

> 16.4 Letter and word spacing: the letter-spacing and word-spacing properties

另一个可能的选择是为每个用户名添加一个尾随空格:

<span class="ellipsiswrap italic">username W&nbsp;</span>

如果& nbsp;太宽,有更窄的选择:

>薄空间:&#8201; (也& thinsp;)
>发空间:&#8202;

点赞