flexbox 可以水平和垂直居中图像而不拉伸它们吗?

Can flexbox horizontally and vertically center images without stretching them?

我想让图像在其容器内水平和垂直居中。如果它们的宽度或高度大于容器的宽度或高度,则让它们在保持比例的情况下自动收缩。

以下CSS代码是我在容器上使用的代码来尝试实现目标:

display: -ms-flexbox;
display: -webkit-flex;
display:         flex;
    -ms-flex-direction: column;
-webkit-flex-direction: column;
        flex-direction: column;
          -ms-flex-pack: center;
-webkit-justify-content: center;
        justify-content: center;

here are three examples on jsFiddle

此外,我知道使用CSS位置和变换也可以达到目的。但是这种方法通常会在调整大小后的图像和容器的边框之间产生 1 个像素的间隙。也就是说,调整大小后的图像无法触及容器的边界,而这是它应该触及的地方。因此我不得不求助于 CSS flexbox.

问题是 align-items is stretch and the initial value of align-self 的初始值是 auto,所以图像被拉伸了。

因此您需要以下其中一项:

.flex-container {
    align-items: center;
}
.flex-item {
    align-self: center;
}

* {
  margin: 0;
  padding: 0;
}
div {
  display: flex; /* Magic begins */
  flex-direction: column;
  justify-content: center; /* Center in main axis */
  align-items: center; /* Center in cross axis */
  margin: 20px auto;
  width: 300px;
  height: 300px;
  border: 2px solid #000;
}
img {
  max-width: 100%;
  max-height: 100%;
}
<div>
  <img src="http://lorempixel.com/400/200/" alt="" />
</div>
<div>
  <img src="http://lorempixel.com/200/400/" alt="" />
</div>
<div>
  <img src="http://lorempixel.com/50/50/" alt="" />
</div>

但请注意,中间的图像仍然有点拉伸。这是因为如果图像比容器高,它们会垂直收缩但不会水平收缩(这与行布局相反)。

为防止出现这种情况,请使用 object-fit(IE 和 Edge 不支持):

img {
  object-fit: contain;
}

* {
  margin: 0;
  padding: 0;
}
div {
  display: flex; /* Magic begins */
  flex-direction: column;
  justify-content: center; /* Center in main axis */
  align-items: center; /* Center in cross axis */
  margin: 20px auto;
  width: 300px;
  height: 300px;
  border: 2px solid #000;
}
img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}
<div>
  <img src="http://lorempixel.com/400/200/" alt="" />
</div>
<div>
  <img src="http://lorempixel.com/200/400/" alt="" />
</div>
<div>
  <img src="http://lorempixel.com/50/50/" alt="" />
</div>