我知道用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/

其他回答

一个纯CSS解决方案,没有包装div或其他无用的代码:

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

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

例如:

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

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

但它可能无法在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/

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


原始图像

垂直剪裁

水平的剪裁

方形容器


实际上,我最近遇到了同样的问题,最后用了一个稍微不同的方法(我不能使用背景图像)。它确实需要一点jQuery来确定图像的方向(我相信你可以使用纯JS代替)。

我写了一篇关于它的博客文章,如果你有兴趣更多的解释,但代码非常简单:

HTML:

<ul class="cropped-images">
  <li><img src="http://fredparke.com/sites/default/files/cat-portrait.jpg" /></li>
  <li><img src="http://fredparke.com/sites/default/files/cat-landscape.jpg" /></li>
</ul>

CSS:

li {
  width: 150px; // Or whatever you want.
  height: 150px; // Or whatever you want.
  overflow: hidden;
  margin: 10px;
  display: inline-block;
  vertical-align: top;
}
li img {
  max-width: 100%;
  height: auto;
  width: auto;
}
li img.landscape {
  max-width: none;
  max-height: 100%;
}

jQuery:

$( document ).ready(function() {

    $('.cropped-images img').each(function() {
      if ($(this).width() > $(this).height()) {
        $(this).addClass('landscape');        
      }
    });

});

使用background-size:cover - http://codepen.io/anon/pen/RNyKzB

CSS:

.image-container {
  background-image: url('http://i.stack.imgur.com/GA6bB.png');
  background-size:cover;
  background-repeat:no-repeat;
  width:250px;
  height:250px;
}  

标记:

<div class="image-container"></div>