Home > Mobile >  Image to fill div by cropping image (no stretch)? With no background image?
Image to fill div by cropping image (no stretch)? With no background image?

Time:10-12

I want my images to fill the div without using background image. Cropping it when necessary, rather than stretching it. Right now, it works...sometimes. But when you shrink the view to mobile view (when the lines are longer than the image, the image doesn't fill the div, empty spaces on top and bottom)

<div class="flex bg-red-500">
  <div class="overflow-hidden block flex-shrink-0 w-1/3">
    <img class="https://www.nerdwallet.com/assets/blog/wp-content/uploads/2017/05/what-is-a-stock-story-770x375.jpg">
  </div>
  <div>
    <h1>Long Title</h1>
    <h2>Some long sub text under the long title. Some long sub text under the long title. Some long sub text under the long title</h2>
  </div>
</div>

CodePudding user response:

If you make the image full width and full height with a display block, you may make use of the object-fit: cover property.

This will make your image cover all the space.

CodePudding user response:

you can do

<div class="flex bg-red-500">
  <div class="overflow-hidden block flex-shrink-0 w-1/3">
    <img style='height: 100%; width: 100%; object-fit: cover' src='https://www.nerdwallet.com/assets/blog/wp-content/uploads/2017/05/what-is-a-stock-story-770x375.jpg'/>
  </div>
  <div>
    <h1>Long Title</h1>
    <h2>Some long sub text under the long title. Some long sub text under the long title. Some long sub text under the long title</h2>
  </div>
</div> 

CodePudding user response:

Since you are using tailwindCSS, please use the below classes on the img tag, to comply with your request.

<link href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.16/tailwind.min.css" rel="stylesheet"/>
<div class="flex bg-red-500 text-white">
  <div class="overflow-hidden block flex-shrink-0 w-1/3">
    <img class="h-full w-full object-cover" src="https://www.nerdwallet.com/assets/blog/wp-content/uploads/2017/05/what-is-a-stock-story-770x375.jpg">
  </div>
  <div class="mx-2">
    <h1>Long Title</h1>
    <h2>Some long sub text under the long title. Some long sub text under the long title. Some long sub text under the long title</h2>
  </div>
</div>

  • Related