使用高度flexbox调整图像大小

时间:2017-07-31 12:54:19

标签: css image css3 flexbox

我有一个带图像的专栏。该列的高度有限,我希望所有图像垂直放入列中。这可能吗?我正在尝试使用flexbox,但还没有成功。

.zoom__images {
  overflow: hidden;
  height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

img {
  width: auto;
  height: auto;
}
<div class="zoom__images">
  <img src="https://s-media-cache-ak0.pinimg.com/736x/42/d4/66/42d466fd73a3b284f49d3020c27cf80e--aloes-martin-omalley.jpg" class="" alt="Simple Picture">
  <img src="https://s-media-cache-ak0.pinimg.com/736x/42/d4/66/42d466fd73a3b284f49d3020c27cf80e--aloes-martin-omalley.jpg" class="" alt="Simple Picture">
  <img src="https://s-media-cache-ak0.pinimg.com/736x/42/d4/66/42d466fd73a3b284f49d3020c27cf80e--aloes-martin-omalley.jpg" class="" alt="Simple Picture">
  <img src="https://s-media-cache-ak0.pinimg.com/736x/42/d4/66/42d466fd73a3b284f49d3020c27cf80e--aloes-martin-omalley.jpg" class="" alt="Simple Picture">
</div>

祝福

2 个答案:

答案 0 :(得分:2)

如果您想为图像选择相同的尺寸

,这将有效

要使flex-items缩小小于其大小,您需要设置flex-basis: 0;min-height: 0。默认值min-height: autoflex-basis: auto;可以防止flex-items缩小小于其大小。 flex-grow: 1使项目增长到相同的值。但是img作为flex-items不会调整大小以保持宽高比,所以我们必须将它们包装起来。演示:

.zoom__images {
  height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.zoom__images > * {
  flex: 1 0 0;
  min-height: 0;
  display: flex;
}

.zoom__images img {
  max-height: 100%;
  margin-left: auto;
  margin-right: auto;
}
<div class="zoom__images">
  <div><img src="https://placehold.it/200x300/a00/fff"></div>
  <div><img src="https://placehold.it/250x175/a00/fff"></div>
  <div><img src="https://placehold.it/250x175/a00/fff"></div>
  <div><img src="https://placehold.it/250x175/a00/fff"></div>
  <div><img src="https://placehold.it/250x175/a00/fff"></div>
  <div><img src="https://placehold.it/100x100/a00/fff"></div>
  <div><img src="https://placehold.it/400x600/a00/fff"></div>
</div>

您还可以为overflow: hidden添加.zoom__images > *以查看未溢出.zoom__images的图片。这不会让它看起来像在其他浏览器中看起来会好得多。

答案 1 :(得分:0)

尝试使用CSS calc()方法。 calc(100 /容器中的图像数量)将调整图像大小&#39;高度可以分享容器高度的100%,这将在所有图像中均匀分配。

&#13;
&#13;
.zoom__images {
  overflow: hidden;
  height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
img {
  width: auto;
  height: calc(100%/4);
}
&#13;
<div class="zoom__images">
        <img src="https://mrose.org/cc/png-test.png" class="" alt="Simple Picture">
        <img src="https://mrose.org/cc/png-test.png" class="" alt="Simple Picture">
        <img src="https://mrose.org/cc/png-test.png" class="" alt="Simple Picture">
        <img src="https://mrose.org/cc/png-test.png" class="" alt="Simple Picture">
    </div>
&#13;
&#13;
&#13;

相关问题