1

Given the following:

<style>
.img_box {
    display: flex;
}
</style>

<div class=img_box>
    <img src=img/>
    <div>Title text of some variable length. Can sometimes be wider than the image, sometimes smaller</div>
</div>

I want to be able to set either a height or width value on the image and have the box shrink to match so it's the same width as the image (minus padding or whatever). The text should wrap and not affect the width of the box at all so whatever the image is sets the width for the box and text.

I know the height of the box will stretch to accommodate wrapped text and that's fine.

not_a_generic_user
  • 1,906
  • 2
  • 19
  • 34

1 Answers1

1

Since you already use display: flex in your .img_box class, you can easily achieve this by setting flex-direction: column and width: min-content. Finally, give the image a desired width.

.img_box {
    display: flex;
    flex-direction: column; 
    width: min-content;
}

.img_box img {
    width: 200px;
}

.img_box div {
    text-align: justify;
}
<div class="img_box">
    <img src="https://randomuser.me/api/portraits/lego/1.jpg" alt="Test Image">
    <div>Title text of some variable length. Can sometimes be wider than the image, sometimes smaller</div>
</div>
Ferris
  • 667
  • 6
  • 16