I want to show an image from an URL with a certain width and height even if it has a different size ratio. So I want to resize (maintaining the ratio) and then cut the image to the size I want. I can resize with html img property and I can cut with background-image. How can I do both? Example: This image: Has the size 800x600 pixels and I want to show like an image of 200x100 pixels With img I can resize the image 200x150px: <img style="width: 200px; height: 150px;" src="http://i.stack.imgur.com/wPh0S.jpg"> That gives me this: <img style="width: 200px; height: 150px;" src="https://i.stack.imgur.com/wPh0S.jpg"> And with background-image I can cut the image 200x100 pixels. <div style="background-image: url('https://i.stack.imgur.com/wPh0S.jpg'); width:200px; height:100px; background-position:center;">&nbsp;</div> Gives me: <div style="background-image:url('https://i.stack.imgur.com/wPh0S.jpg'); width:200px; height:100px; background-position:center;">&nbsp;</div> How can I do both? Resize the image and then cut it the size I want?


当前回答

你试过用这个吗?

.centered-and-cropped { object-fit: cover }

我需要调整图像的大小,中心(垂直和水平),然后裁剪它。

我很高兴地发现,它可以在一个css行中完成。 在这里查看示例:http://codepen.io/chrisnager/pen/azWWgr/?editors=110


下面是这个例子的CSS和HTMLcode:

.居中剪裁{对象合身:封面} <标题>原始h1 > < / <img height="200" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3174/bear.jpg" alt="熊"> <标题> object-fit:封面h1 > < / <img class="center -and-裁剪" width="200" height="200" style="border-radius:50%" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3174/bear.jpg" alt="熊">

其他回答

img {
  position: absolute;
  clip: rect(0px, 140px, 140px, 0px);
}
<img src="w3css.gif" width="100" height="140" />

我所做的是创建一个服务器端脚本,它将在服务器端调整大小和裁剪图片,这样它就会在互联网上发送更少的数据。

它相当简单,但如果有人感兴趣,我可以挖掘并发布代码(asp.net)

您可以将img标记放在div标记中,但我建议不要在浏览器中缩放图像。它在大多数时候都做得很糟糕,因为浏览器的缩放算法非常简单。最好先在Photoshop或ImageMagick中进行缩放,然后将其漂亮地提供给客户端。

如果您正在使用<img>标记,那么Object-fit可能会帮助您

下面的代码将为您裁剪图像。你可以尝试一下合身的衣服

img {
  object-fit: cover;
  width: 300px;
  height: 337px;
}

你可以把两种方法结合起来使用。

.crop { 宽度:200 px; 身高:150 px; 溢出:隐藏; } .crop img { 宽度:400 px; 身高:300 px; Margin: -75px 00 -100px; } < div class = "作物”> <img src="https://i.stack.imgur.com/wPh0S.jpg" alt="唐老鸭"> < / div >

您可以使用负边距在<div/>内移动图像。