【问题标题】:How do I prevent multiline text from filling the entire width of the parent element如何防止多行文本填充父元素的整个宽度
【发布时间】:2021-07-10 12:28:39
【问题描述】:

假设我有一个具有固定宽度的容器元素。我有一个带有显示内联块的内容元素,可以包含一些文本。此文本可能太大,以至于必须填充多行。这样做的问题是,多行文本的默认行为是将元素增加到父元素的完整宽度。

想象一下下面的例子:

HTML:

<div class="container">
  <div class="content">
    Firstreallongword11 Secondalsolongword22 Thirdwordthatisconsiderablylonger
  </div>
</div>

CSS:

.container {
  width: 260px;
  border: solid blue 1px;
}
.content {
  display: inline-block;
  background: red;
}

因为这些是长词,它们将被放置在多行中。我对.content 元素的期望是,它将增长到单行上最大单词的最大宽度。 但是正如你所看到的,因为它由多行组成,所以元素会增长到.container 的最大宽度。

FIDDLE

我想要实现的是,.content 获得单行上最大项目的宽度,就像使用单个 lin 一样:

FIDDLE

有什么方法可以用纯 css/html 实现吗?

【问题讨论】:

标签: css text multiline


【解决方案1】:

简单的答案是:不,纯 CSS 无法做到这一点。

但无论如何这里有一个解决方案,这有点小技巧:它使用display: table-cell; 作为.content 元素,以及一个相当小的width 值(它将调整为最长单词的实际值在这种情况下,就像min-width 设置一样):

.container {
  width: 260px;
  border: solid blue 1px;
}
.content {
  display: table-cell;
  width: 100px;
  background: red;
}
<div class="container">
  <div class="content">
    Firstreallongword11 Secondalsolongword22 Thirdwordthatisconsiderablylonger
  </div>
</div>

【讨论】:

    猜你喜欢
    • 2018-10-25
    • 2012-06-13
    • 2013-05-13
    • 2018-01-04
    • 2016-08-18
    • 1970-01-01
    • 2017-04-13
    • 2017-02-23
    • 2021-12-18
    相关资源
    最近更新 更多