CSS显示调整大小并裁剪的图像

老子叫甜甜 提交于 2020-03-18 12:30:54

某厂面试归来,发现自己落伍了!>>>

我想显示具有特定宽度和高度的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;">&nbsp;</div>

给我:

<div style="background-image:url('https://i.stack.imgur.com/wPh0S.jpg'); width:200px; height:100px; background-position:center;">&nbsp;</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


这是该示例的CSSHTML代码:

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!