自适应宽度的div中如何实现文字自动换行

4

我有一堆响应式的img元素(它们根据图片和视口大小进行调整大小)在垂直列表上。

每个图像需要底部的描述,但不应水平扩展容器。(我目前无法将文本换行)

在第一个示例中,文本扩展了容器的宽度。使用第二个示例,我不得不添加<br>标签来模拟我想要的效果。

Example

是否有办法通过CSS控制文本元素的换行?

另外,这是这个示例的JSFiddle链接。

1个回答

6

您可以使用 width: min-content 来设置 .box 的宽度,例如:

.box {
  width: min-content;
}

请查看下面的代码片段或更新的 JSFiddle链接:

.box {
  width: min-content;
  display: table;
  position: relative;
  background: #334b64;
  margin: 0px auto 20px auto;
  box-shadow: 0px 0px 50px rgba(29, 80, 123, 0.3);
}

.text {
  color: white;
  font-size: 14;
  text-align: center;
  position: relative;
  width: 100%;
  height: auto;
  word-wrap: break-word;
  white-space: pre-wrap
}
<div class="container-fluid container-screenshot">
  <div class="img-responsive-parent">
    <div class="box">
      <img class="img-responsive" src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a9/Guarita_-_Torres_-_Brasil_.JPG/320px-Guarita_-_Torres_-_Brasil_.JPG" />
      <h4 class="text">Example text. This text should wrap, not expanding the div.</h4>
    </div>

    <div style="display:table; position: relative; background: #334b64; margin: 0px auto 30px auto; box-shadow: 0px 0px 50px rgba(29, 80, 123, 0.3);">
      <img class="img-responsive" src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a9/Guarita_-_Torres_-_Brasil_.JPG/320px-Guarita_-_Torres_-_Brasil_.JPG" />
      <h4 class="text">How it should behave:<br>A new line should be created without manually<br>adding a BR tag</h4>
    </div>
  </div>
</div>

希望这能帮到您!

1
建议 OP 在实现 min-content 之前考虑 http://caniuse.com/#search=min-content,因为它在某些浏览器上存在限制。 - Robert
是的,不是所有浏览器都支持 min-content。我最终使用了一个表格。无论如何,谢谢。 :) - Nicke Manarin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接