我想显示具有特定宽度和高度的URL的图像,即使它具有不同的尺寸比例。 所以我想调整大小(保持比例),然后将图像切成我想要的大小。
我可以使用html img
属性调整大小,也可以使用background-image
进行裁剪。
我该怎么办?
例:
这个图片:

尺寸为800x600
像素,我想显示为200x100
像素的图像
使用img
我可以将图像尺寸调整为200x150px
:
<img
style="width: 200px; height: 150px;"
src="http://i.stack.imgur.com/wPh0S.jpg">
这给了我这个:
<img style="width: 200px; height: 150px;" src="https://i.stack.imgur.com/wPh0S.jpg">
使用background-image
我可以将图像切成200x100
像素。
<div
style="background-image:
url('https://i.stack.imgur.com/wPh0S.jpg');
width:200px;
height:100px;
background-position:center;"> </div>
给我:
<div style="background-image:url('https://i.stack.imgur.com/wPh0S.jpg'); width:200px; height:100px; background-position:center;"> </div>
我该怎么办?
调整图像大小,然后将其切成我想要的大小?
#1楼
<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;
}
#2楼
谢谢sanchothefat。
我对你的回答有所改善。 由于裁剪是针对每个图像量身定制的,因此此定义应使用HTML而不是CSS。
<div style="overflow:hidden;">
<img src="img.jpg" alt="" style="margin:-30% 0px -10% 0px;" />
</div>
#3楼
<div class="crop">
<img src="image.jpg"/>
</div>
.crop {
width: 200px;
height: 150px;
overflow: hidden;
}
.crop img {
width: 100%;
/*Here you can use margins for accurate positioning of cropped image*/
}
#4楼
img {
position: absolute;
clip: rect(0px, 140px, 140px, 0px);
}
<img src="w3css.gif" width="100" height="140" />
#5楼
你试过用这个吗?
.centered-and-cropped { object-fit: cover }
我需要调整图像大小,居中(垂直和水平方向),然后进行裁切。
我很高兴发现它可以在单个CSS行中完成。 在此处检查示例: http : //codepen.io/chrisnager/pen/azWWgr/?editors=110
这是该示例的CSS
和HTML
代码:
.centered-and-cropped { object-fit: cover }
<h1>original</h1> <img height="200" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3174/bear.jpg" alt="Bear"> <h1>object-fit: cover</h1> <img class="centered-and-cropped" width="200" height="200" style="border-radius:50%" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3174/bear.jpg" alt="Bear">
来源:oschina
链接:https://my.oschina.net/u/3797416/blog/3197410