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?


当前回答

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

.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/>内移动图像。

其他回答

.imgContainer {
  overflow: hidden;
  width: 200px;
  height: 100px;
}
.imgContainer img {
  width: 200px;
  height: 120px;
}
<div class="imgContainer">
  <img src="imageSrc" />
</div>

包含的div本质上是通过隐藏溢出来裁剪图像。

生活例子: https://jsfiddle.net/de4Lt57z/

HTML:

<div class="crop">
  <img src="example.jpg" alt="..." />
</div>

CSS:

    .crop img{
      width:400px;
      height:300px;
      position: absolute;
      clip: rect(0px,200px, 150px, 0px);
      }

解释: 在这里,图像是根据图像的宽度和高度值调整大小。裁剪是通过剪辑属性完成的。

有关剪辑属性的详细信息请参见: http://tympanus.net/codrops/2013/01/16/understanding-the-css-clip-property/

在之前的答案中增加了一个小的内容,包括对象合身:封面:

对象的位置

您可以使用object-position属性更改替换元素的内容对象在元素框中的对齐方式。

.trimmed-cover { object-fit:封面; 宽度:100%; 身高:177 px; 物体位置:中心40%; } <img class="trim -cover" src="http://i.stack.imgur.com/wPh0S.jpg">

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

.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/>内移动图像。

在裁剪类中,放置你想要显示的图像大小:

.crop {
    width: 282px;
    height: 282px;
    overflow: hidden;
}
.crop span.img {
    background-position: center;
    background-size: cover;
    height: 282px;
    display: block;
}

html看起来像这样:

<div class="crop">
    <span class="img" style="background-image:url('http://url.to.image/image.jpg');"></span>
</div>