Home > front end >  Prevent image from expanding horizontal flex box
Prevent image from expanding horizontal flex box

Time:01-16

enter image description here

I have a horizontal flex box with 3 columns. The black column (1/3rd on the left) is an image, the white column (1/3rd center) is text and the blue column (1/3rd right) is text.

The issue is that the text columns are by themselves just as high as the black stripe overlaying the white/blue boxes. The problem that happens is, that my image (black col on the left) stretches the text columns to become as big as itself.

I assume the image automatically wants to preserve the aspect ratio and this affects the overall height of the flexbox.

My goal is: I would like to keep the flexbox as high as the largest text column, but the image column should not grow the flexbox taller. In Tailwind, I've added object-cover and object-center on the image (the idea is that the image fills the gray stripe on the black box, covering it). Basically, the image should have the dimensions of the gray box via object-fit.

I've tried setting the image height to max-content and playing around with all kinds of height values, but I haven't found a decent solution yet. Can anyone help?

<div >
    <div >
        <img  />
    </div>
    <div >
        <p>Short Text</p>
    </div>
    <div >
        <p>Short Text</p>
    </div>
</div>

CodePudding user response:

Removing the items-center class makes flex items the same height. To prevent img from changing the left column's height its position should be absolute. To define the position of img the parent tag should be relative. Two classes of translate-x-1/2 and right-1/2 are added to bring the img center.

<script src="https://cdn.tailwindcss.com/"></script>
<div >
    <div >
        <img  src="https://cdn.sstatic.net/Sites/stackoverflow/Img/apple-touch-icon.png" />
    </div>
    <div >
        <p>Short Text</p>
    </div>
    <div >
        <p>Short Text</p>
    </div>
</div>

  •  Tags:  
  • Related