CSS - 如果图像已经是正方形然后调整大小,如何将图像裁剪为正方形 [英] CSS - How to crop an image to a square, if it's already square then resize it

查看:281
本文介绍了CSS - 如果图像已经是正方形然后调整大小,如何将图像裁剪为正方形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 250宽度和250高度的图片,我想将它裁剪为 90x90



它会显示图像中的像素,但是如果它是矩形,并且如果它是方形的,我会裁剪它,所以我该如何去做?



这是裁剪图像的CSS代码,但是如何调整它的大小?

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


解决方案

方法1



适用于水平矩形图像(宽度较大),如果需要垂直图像,可以将 height:100%更改为 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%;
}

示例小提琴 第一幅图像被调整大小,第二幅被裁剪

方法2



适用于所有图片尺寸

HTML

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

CSS

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

示例小提琴


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);
}

解决方案

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

这篇关于CSS - 如果图像已经是正方形然后调整大小,如何将图像裁剪为正方形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆