CSS - How to crop an image to a square, if it's already square then resize it

梦想与她 提交于 2019-12-10 23:22:31

问题


Let's say that I have an image with 250 width and 250 height and I want to crop it to 90x90

It will show me pixels from the image, but I want to crop it if it is rectangle and resize it if it's square, So how can I do it?

This is the CSS code that crops the image, but how do I resize it?

.image{ 
    width:90px;
    height:90px;
}
.image{
    display: block;
    overflow:hidden;
    clip:rect(0px,90px,90px,0px);
}

回答1:


METHOD 1

Will work for horizontal rectangle images (larger in width), if you need vertical images you can change height:100% for width:100%

HTML

<div class="img-container">
    <img src="http://lorempixel.com/250/250" />
</div>

CSS

.img-container {
    width: 90px;
    height: 90px;
    overflow: hidden;
}
.img-container img {
    height: 100%;
}

Example fiddle First image is resized, second is cropped

METHOD 2

Works for all image sizes

HTML

<div class="img" style="background-image:url('http://lorempixel.com/250/250')"></div>

CSS

.img{
    width: 90px;
    height: 90px;
    background-size: cover;
}

Example fiddle




回答2:


try this

<div style="width:90px; height:90px; overflow:hidden;">
<img src="Message.png"/>
</div>


来源:https://stackoverflow.com/questions/17745559/css-how-to-crop-an-image-to-a-square-if-its-already-square-then-resize-it

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