My code below is taken nearly verbatim from the example at https://getbootstrap.com/docs/5.2/utilities/flex/#media-object. It should create a box with a picture on the left and some text on the right:
<div class="mycard border border-dark m-3 p-3 d-flex align-items-center" style="width: 33%;">
<div class="flex-shrink-0">
<img src="https://s3.amazonaws.com/cdn.sidsavage.com/images/prods/popup/P8889.jpg">
</div>
<div class="flex-grow-1 ms-3">
This is some content from a media component. You can replace this with any content and adjust it as needed.
</div>
</div>
Here’s the catch: the image I used is really huge, which causes the box to become messed up. I could fix this by adding style="max-height: 70px;"
to the img tag, but I don’t know in advance how big to make the image. I want the text to dictate the height of the box, and the image to be sized appropriately for that box height.
You can play with my example here: https://codepen.io/Meekro/pen/oNQGMPM
2
Answers
Maybe using columns to make the space for the image and using
background-size: contain
to keep the image within the boundaries of the container div might work for you.See sample code below
In pure css you can just add a width to your image:
height will automatically calculate. If you know the dimensions it’s best to use aspect-ratio to prevent repaints/recalculations.
Where 4/3 is your known aspect ratio.
EDIT: I didn’t read the height part of your question lol.
If the parent has a set height, just do: