4

I have a bunch of responsive img elements (they resize based on image and viewport size) on a vertical list.

Each image needs a description at the bottom, but it should not expand horizontally the container. (I'm currently not able to wrap the text to a new line)

On the first example, the text expands the width of the container. With the second example, I had to add <br> tags to simulate what I want.

Example

Is there any way to control the wrap of the text element (by using CSS)?

Btw, here's the JSFiddle for this example.

Nicke Manarin
  • 3,026
  • 4
  • 37
  • 79

1 Answers1

6

You can use width: min-content to the .box for this, like:

.box {
  width: min-content;
}

Have a look at the snippet below or the updated fiddle:

.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>

Hope this helps!

Saurav Rastogi
  • 9,575
  • 3
  • 29
  • 41
  • 1
    Recommend OP consider http://caniuse.com/#search=min-content before implementing `min-content` as it does have browser limitations. – Robert Nov 02 '17 at 19:09
  • Yeah, `min-content` is not supported by all browsers. I ended up using a table. Thanks anyway. :) – Nicke Manarin Nov 02 '17 at 23:57