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.
2
Answers
you can achive this using CSS
object-fit
property to controll the image size andflex
property to property to make the container adjust its size to fit the imagehere is a example code that i think archive you desire
note that in above example
object-fit
property is set tocontain
that ensures the image is scale down to fit while maintaing its aspect ratio. alsoheight
property is set to image size whilewidth
is set toauto
that furthermore maintain aspect ratio of the imageThe CSS property
flex
is set to1
applied to the container holding the text means that it will take up all the available space in the container, regardless of how long the text is. By adding themargin-left
property to the container, we can create some space between the image and the text.Since you already use
display: flex
in your.img_box
class, you can easily achieve this by settingflex-direction: column
andwidth: min-content
. Finally, give the image a desiredwidth
.