skip to Main Content

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


  1. you can achive this using CSS object-fit property to controll the image size and flex property to property to make the container adjust its size to fit the image

    here is a example code that i think archive you desire

    <style>
    .img_box {
        display: flex;
    }
    .img_box img {
        object-fit: contain;
        height: 200px; /* set the height or width of the image here */
        width: auto;
    }
    .img_box div {
        margin-left: 10px; /* add some spacing between the image and the text */
        flex: 1; /* make the text container fill the remaining space */
    }
    </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>
    

    note that in above example object-fit property is set to contain that ensures the image is scale down to fit while maintaing its aspect ratio. also height property is set to image size while width is set to auto that furthermore maintain aspect ratio of the image

    The CSS property flexis set to 1 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 the margin-left property to the container, we can create some space between the image and the text.

    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search