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

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

我想把这个:

到这个:


当前回答

现在你可以使用纵横比:

img {
   aspect-ratio: 1 / 1;
}

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

其他回答

我用了不同的方法。你基本上需要裁剪矩形图像,使其适合正方形,这就是它的全部。最好的方法是如果图像宽度大于高度,那么你从图像的左边和右边稍微裁剪图像。如果图像高度大于图像宽度,则裁剪图像底部。这是我的解决方案。不过我需要PHP的一点帮助。

    <div style="position: relative; width: 154px; height: 154px; overflow: hidden;">
<?php 
        //get image dimmensions whichever way you like. I used imgaick
        $image = new Imagick("myimage.png");
        $width = $image->getImageWidth();  
        $height = $image->getImageHeight(); 
        if($width > $height){
 ?>
        <img src="myimage.png" style="display: block; position: absolute; top: 0px; left: 50%; transform: translateX(-50%); -ms-transform: translateX(-50%); -webkit-transform: translateX(-50%); height: 100%; " />
 <?php
        }else{
 ?>
        <img src="myimage.png" style="display: block; position: absolute; top: 0px; left: 0px; width: 100%; " />
 <?php
        }
 ?>

    </div>

把你的图像放在一个div中。 给你的div显式的正方形尺寸。 将div的CSS overflow属性设置为hidden (overflow:hidden)。 将您的想象放在div中。 利润。

例如:

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

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

.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解决方案,没有包装div或其他无用的代码:

img {
  object-fit: cover;
  width: 230px;
  height: 230px;
}

适合对象:封面正好可以满足你的需要。

但它可能无法在IE/Edge上运行。如下所示,用CSS修复它,使其适用于所有浏览器。

我采用的方法是在容器中使用absolute定位图像,然后使用组合将其放在正中央:

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

一旦它在中心,我给图像,

// For vertical blocks (i.e., where height is greater than width)
height: 100%;
width: auto;

// For Horizontal blocks (i.e., where width is greater than height)
height: auto;
width: 100%;

这使得图像得到对象适合:覆盖的效果。


下面是上述逻辑的演示。

https://jsfiddle.net/furqan_694/s3xLe1gp/

这种逻辑适用于所有浏览器。


原始图像

垂直剪裁

水平的剪裁

方形容器