在单行图像中裁剪到最短图像高度?

时间:2018-01-01 23:07:38

标签: html css image grid row

是否可以将图像裁剪为单行图像中图像的最短高度?如果是这样,这可以单独使用CSS吗?

这是我想要完成的一个例子:

enter image description here

以下是我目前正在处理的代码:



.container {
  width: 100%;
  margin: 0 auto;
}

.row {
  width: 100%;
  background: black;
  display: flex;
  align-items: center;
  overflow: auto;
}

.row .item {
  width: 33.33333%;
}

.row img {
  display: block;
  object-fit: cover;
  width: 100%;
}

<div class="container">
  <div class="row">
    <div class="item">
      <img src="https://78.media.tumblr.com/708bb6dcdaf359fd2ea83d11a0b5b4b8/tumblr_oyslstg5xk1unhdoco3_r1_1280.jpg" />
    </div>
    <div class="item">
      <img src="https://78.media.tumblr.com/c49ef0b40483c35ad3b6898c0e037e11/tumblr_oyslstg5xk1unhdoco2_r1_1280.jpg" />
    </div>
    <div class="item">
      <img src="https://78.media.tumblr.com/737456a69c07da1a9a2784506f62dce9/tumblr_oyslstg5xk1unhdoco9_r1_1280.jpg" />
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

任何解决方案或建议?

1 个答案:

答案 0 :(得分:2)

除非您可以在后端脚本上处理高度并在输出时在容器上设置高度,否则最好使用JS。

无论如何,这里有一点JS可以达到你想要的效果:

&#13;
&#13;
const items = [...document.querySelectorAll('.item')];
const row = document.querySelector('.row');

function normalizeImages(images, container) {
  const shortestItem = images.reduce((smallest, element) => {
    return element.clientHeight < smallest.clientHeight ? element : smallest;
  });

  container.style.height = `${shortestItem.clientHeight}px`;
}

normalizeImages(items, row);

window.addEventListener('resize', () => normalizeImages(items, row));
&#13;
.container {
  width: 100%;
  margin: 0 auto;
}

.row {
  width: 100%;
  background: black;
  display: flex;
  align-items: center;
  overflow: hidden;
}

.row .item {
  flex-basis: 33.33333%;
}

.row img {
  display: block;
  width: 100%;
}
&#13;
<div class="container">
  <div class="row">
    <div class="item">
      <img src="https://78.media.tumblr.com/708bb6dcdaf359fd2ea83d11a0b5b4b8/tumblr_oyslstg5xk1unhdoco3_r1_1280.jpg" />
    </div>
    <div class="item">
      <img src="https://78.media.tumblr.com/c49ef0b40483c35ad3b6898c0e037e11/tumblr_oyslstg5xk1unhdoco2_r1_1280.jpg" />
    </div>
    <div class="item">
      <img src="https://78.media.tumblr.com/737456a69c07da1a9a2784506f62dce9/tumblr_oyslstg5xk1unhdoco9_r1_1280.jpg" />
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

请注意,少量CSS已更改为隐藏.row元素上的溢出