我有一个DIV,使用CSS flexBox缩放到可用的高度.在这个DIV中,我想在DIV中扩展两个维度.这意味着应该缩小其纵横比,并且小于相应DIV尺寸的尺寸应该居中.
我可以使图像跟随DIV的宽度,但不是高度.因此,肖像图像从DIV界限中逃脱.
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;
除此之外,我找不到不涉及脚本的方式.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。