要通过裁剪图像(无拉伸)来填充 div 的图像?没有背景图片?

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

我希望我的图像在不使用背景图像的情况下填充 div。必要时裁剪它,而不是拉伸它。现在,它可以工作……有时。但是当你将视图缩小到移动视图时(当线条比图像长时,图像不会填充 div,顶部和底部的空白区域)

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

如果用显示块使图像全宽和全高,您可以使用object-fit: cover 属性。

这将使您的图像覆盖所有space。

你可以做到

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

由于您使用的是 tailwindCSS,请在 img 标签上使用以下 类 以符合您的要求。

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