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

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

我想把这个:

到这个:


当前回答

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

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

其他回答

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

<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标签中……

HTML:

<div class="thumb1">
</div>

CSS:

.thumb1 { 
  background: url(blah.jpg) 50% 50% no-repeat; /* 50% 50% centers image in div */
  width: 250px;
  height: 250px;
}

.thumb1:hover { YOUR HOVER STYLES HERE }

编辑:如果div需要链接到某个地方,只需调整HTML和样式如下:

HTML:

<div class="thumb1">
<a href="#">Link</a>
</div>

CSS:

.thumb1 { 
  background: url(blah.jpg) 50% 50% no-repeat; /* 50% 50% centers image in div */
  width: 250px;
  height: 250px;
}

.thumb1 a {
  display: block;
  width: 250px;
  height: 250px;
}

.thumb1 a:hover { YOUR HOVER STYLES HERE }

注意,这也可以修改为响应,例如%宽度和高度等。

现在你可以使用纵横比:

img {
   aspect-ratio: 1 / 1;
}

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

使用CSS: overflow:

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

使用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>