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;"> </div> Gives me: <div style="background-image:url('https://i.stack.imgur.com/wPh0S.jpg'); width:200px; height:100px; background-position:center;"> </div> How can I do both? Resize the image and then cut it the size I want?
当前回答
谢谢sanchothefat。
我对你的回答有改进的地方。由于裁剪是非常适合每一个图像,这个定义应该在HTML而不是CSS。
<div style="overflow:hidden;">
<img src="img.jpg" alt="" style="margin:-30% 0px -10% 0px;" />
</div>
其他回答
img {
position: absolute;
clip: rect(0px,60px,200px,0px);
}
.imgContainer {
overflow: hidden;
width: 200px;
height: 100px;
}
.imgContainer img {
width: 200px;
height: 120px;
}
<div class="imgContainer">
<img src="imageSrc" />
</div>
包含的div本质上是通过隐藏溢出来裁剪图像。
在之前的答案中增加了一个小的内容,包括对象合身:封面:
对象的位置
您可以使用object-position属性更改替换元素的内容对象在元素框中的对齐方式。
.trimmed-cover { object-fit:封面; 宽度:100%; 身高:177 px; 物体位置:中心40%; } <img class="trim -cover" src="http://i.stack.imgur.com/wPh0S.jpg">
有像Filestack这样的服务可以帮你做这件事。
它们获取你的图像url,并允许你使用url参数来调整它的大小。这很简单。
将图像大小调整为200x100,但保持纵横比后,图像将如下所示
整个url看起来像这样
https://process.filestackapi.com/AhTgLagciQByzXpFGRI0Az/resize=width:200/crop=d:[0,25,200,100]/https://i.stack.imgur.com/wPh0S.jpg
但重要的是
resize=width:200/crop=d:[0,25,200,100]
<p class="crop"><a href="http://templatica.com" title="Css Templates">
<img src="img.jpg" alt="css template" /></a></p>
.crop {
float: left;
margin: .5em 10px .5em 0;
overflow: hidden; /* this is important */
position: relative; /* this is important too */
border: 1px solid #ccc;
width: 150px;
height: 90px;
}
.crop img {
position: absolute;
top: -20px;
left: -55px;
}