我知道用CSS修改图像是不可能的,这就是为什么我把裁剪放在引号里的原因。

我想做的是采用矩形图像,并使用CSS使它们看起来像正方形,而不扭曲图像。

我想把这个:

到这个:


当前回答

我有一个类似的问题,不能“妥协”的背景图像。 我想到了这个。

<div class="container">
    <img src="http://lorempixel.com/800x600/nature">
</div>

.container {
    position: relative;
    width: 25%; /* whatever width you want. I was implementing this in a 4 tile grid pattern. I used javascript to set height equal to width */
    border: 2px solid #fff; /* just to separate the images */
    overflow: hidden; /* "crop" the image */
    background: #000; /* incase the image is wider than tall/taller than wide */
}

.container img {
    position: absolute;
    display: block;
    height: 100%; /* all images at least fill the height */
    top: 50%; /* top, left, transform trick to vertically and horizontally center image */
    left: 50%;
    transform: translate3d(-50%,-50%,0);
}

//assuming you're using jQuery
var h = $('.container').outerWidth();
$('.container').css({height: h + 'px'});

希望这能有所帮助!

例子: https://jsfiddle.net/cfbuwxmr/1/

其他回答

现在你可以使用纵横比:

img {
   aspect-ratio: 1 / 1;
}

它在现代浏览器中也有广泛的支持: https://caniuse.com/mdn-css_properties_aspect-ratio

如果图像在一个具有响应宽度的容器中:

.rect-img-container { 位置:相对; } {后.rect-img-container:: 内容:“”; 显示:块; padding-bottom: 100%; } .rect-img { 位置:绝对的; 宽度:100%; 高度:100%; object-fit:封面; } < div class = " rect-img-container”> <img class="rect-img" src="https://picsum。照片/ id / 0/367/267”alt = " " > < / div >

(编辑:从sass更新为纯css) (编辑:添加了虚拟图像供参考)

查看CSS的纵横比

https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio

.square-image { 宽度:50%; 背景图片:url (https://picsum.photos/id/0/367/267); background-size:封面; 背景位置:中心; 比例:1/1; } < div class = "方形图像“> < / div >

您也可以使用常规的img标签,如下所示

.square-image { 宽度:50%; object-fit:封面;/*需要防止图像拉伸,使用对象位置属性调整可见区域*/ 比例:1/1; } < img src = " https://picsum。照片/ id / 0/367/267”class = "方形图像" / >

使用CSS: overflow:

.thumb {
   width:230px;
   height:230px;
   overflow:hidden
}

我有一个类似的问题,不能“妥协”的背景图像。 我想到了这个。

<div class="container">
    <img src="http://lorempixel.com/800x600/nature">
</div>

.container {
    position: relative;
    width: 25%; /* whatever width you want. I was implementing this in a 4 tile grid pattern. I used javascript to set height equal to width */
    border: 2px solid #fff; /* just to separate the images */
    overflow: hidden; /* "crop" the image */
    background: #000; /* incase the image is wider than tall/taller than wide */
}

.container img {
    position: absolute;
    display: block;
    height: 100%; /* all images at least fill the height */
    top: 50%; /* top, left, transform trick to vertically and horizontally center image */
    left: 50%;
    transform: translate3d(-50%,-50%,0);
}

//assuming you're using jQuery
var h = $('.container').outerWidth();
$('.container').css({height: h + 'px'});

希望这能有所帮助!

例子: https://jsfiddle.net/cfbuwxmr/1/