html – Flexbox图像缩放到高度并保持纵横比

我有一个DIV,使用CSS flexBox缩放到可用的高度.在这个DIV中,我想在DIV中扩展两个维度.这意味着应该缩小其纵横比,并且小于相应DIV尺寸的尺寸应该居中.

我可以使图像跟随DIV的宽度,但不是高度.因此,肖像图像从DIV界限中逃脱.

这是一个jsFiddle来演示这个问题.

html,body {
  height: 100%;
  margin: 0;
}
.container {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.Box {
  flex: 1 1 auto;
  display: flex;
  justify-content: center;
  align-items: center;
}
.Box img {
  width: auto;
  height: auto;
  max-width: 90%;
  max-height: 90%;
}
<div class="container">
  <div class="Box"></div>
  <div class="Box" style="background: pink;">
    <img src="//dummyimage.com/300" />
  </div>
  <div class="Box"></div>
</div>

解决方法

如果你可以从flex更改为block:

https://jsfiddle.net/svArtist/ug6eoxfs/

正如@janfoeh所指出的,使用对象拟合:包含使它成为可能:

body,html {
    height: 100%;
    margin: 0;
    padding: 0;
    overflow:hidden;
    position:relative;
}

.container {
    width: 100%;
    max-width: 100%;
    height: 100%;
    max-height: 100%;
}

.Box {
    background: yellow;
    width: 100%;
    padding: 0 5%;
    Box-sizing:border-Box;
    max-width: 100%;
    height: 100%;
    max-height:100%;
    position:relative;
}

.Box img {
    height:100%;
    max-height: 100%;
    width: auto;
    max-width: 100%;
    margin: auto;
    position:absolute;
    top:0%;
    bottom:0%;
    left:0%;
    right:0%;
    display:block;
    object-fit: contain;
}

如果需要Flex布局,作为最后的手段,您可以考虑使用背景图像,这使得整个事情变得非常简单:https://jsfiddle.net/svArtist/e1c2tLme/

background: url(http://placehold.it/300) no-repeat center center;
    background-size: contain;

除此之外,我找不到不涉及脚本的方式.

相关文章

vue阻止冒泡事件 阻止点击事件的执行 &lt;div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些