search

Home  >  Q&A  >  body text

How to achieve responsive design while maintaining fixed image dimensions?

<p>I have the following CSS (using Bootstrap) to resize an image so that it fits into a 16:9 container without stretching: </p> <pre class="brush:php;toolbar:false;"><span class="bg-dark d-flex justify-content-center align-items-center style="width: 384px; height: 216px"> <img :src="slotProps.item.itemImageSrc" :alt="slotProps.item.alt" style="max-width: 100%; max-height: 100%" /> </span></pre> <p>This method works, but when I use it in a Bootstrap grid, the image overflows the grid (I think because I fixed the size with absolute values). How can I make the image resize but not overflow? </p> <p>(Background info: This is being used in a gallery component, the images coming in may be different sizes, so I need to resize them all to display in the same size container, there may be black ones on the top or bottom margin)</p>
P粉739706089P粉739706089469 days ago442

reply all(1)I'll reply

  • P粉191610580

    P粉1916105802023-08-17 00:28:09

    To solve this problem, you can use the object-fit CSS property. The object-fit attribute specifies how the image should be resized to fit its container. The cover value will resize the image to fill the entire container while maintaining its aspect ratio.

    <span class="bg-dark d-flex justify-content-center align-items-center">
      <img
        :src="slotProps.item.itemImageSrc"
        :alt="slotProps.item.alt"
        style="object-fit: cover; max-width: 100%; max-height: 100%"
      />
    </span>

    reply
    0
  • Cancelreply