skip to Main Content

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


  1. 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

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
    
    <div class="card">
      <div class="card-body">
        <div class="row">
        <div class="col-2" id="forImg" style='background: white url("https://s3.amazonaws.com/cdn.sidsavage.com/images/prods/popup/P8889.jpg") no-repeat center;
       background-size: contain;'>
        </div>    
        <div class="col-10">
          <p class="card-text">
          This is some content from a media component. You can replace this with any content and adjust it as needed.
        </p>
      <p class="card-text">
          This is some content from a media component. You can replace this with any content and adjust it as needed.
        </p>
        </div>
      </div>
    </div>
    Login or Signup to reply.
  2. In pure css you can just add a width to your image:

    style="max-width:100%;"
    

    height will automatically calculate. If you know the dimensions it’s best to use aspect-ratio to prevent repaints/recalculations.

    style="max-width:100%;aspect-ratio:4/3;"
    

    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:

    style="max-height:100%;max-width:100%;"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search