将图像居中显示在父容器内

5
想要在不显式设置其父元素高度的情况下使图像在垂直和水平方向上居中。希望最高图像的高度成为其父级容器的高度,并使其他所有同级图像也处于中心位置。
最终结果将看起来像这个http://fiddle.jshell.net/4myos5s2/,其中高图像设置了父元素的高度。
使用flexbox但仍需要为父元素定义高度:http://jsfiddle.net/danield770/vc4cd02a/
div {
    display: flex;
    justify-content: center; /* align horizontal */
    align-items: center; /* align vertical */
    border: 1px solid green;
    width: 100%;
    height: 80vw;
}

<div>
    <img alt="No, he'll be an engineer." src="http://placehold.it/350x150" />
</div>

2
尝试这个解决方案:https://dev59.com/NGMl5IYBdhLWcg3wTlcl - user1012181
1
@user1012181 谢谢!那个解决方案起作用了。我会把它发布为答案。 - Steve
1个回答

2
如果您希望所有容器的大小都与最高的图像相同,则必须设置容器div的大小...
您可以使用JavaScript将所有flexbox容器div的大小设置为图像集的最大高度和宽度。
然后,通过在容器上设置justify-content:centeralign-items:center来使用flexbox将图像居中对齐。
示例代码和演示:

$(window).load(function(){

  function log(){console.log.apply(console,arguments);}

  $imgs=$('img');

  // calc maxWidth & maxHeight
  var maxWidth=0;
  var maxHeight=0;
  $imgs.each(function(){
    var img=this;
    if(img.clientWidth>maxWidth){maxWidth=img.clientWidth;}
    if(img.clientHeight>maxHeight){maxHeight=img.clientHeight;}
  });

  // wrap each img in a div with class of 'container'
  $('img').wrap('<div class=container></div>');

  $('.container').css({
    'width':maxWidth+'px',
    'height':maxHeight+'px',
  });  


}); // end $(function(){});
body{ background-color: ivory; }
.container{
  display:flex;
  margin:10px;
  border:1px solid blue;
  justify-content:center;
}
img{
  flex:0 1 auto;
  align-self:center;
  border:1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>I'm the tallest image</h4>
<img src="https://dl.dropboxusercontent.com/u/139992952/multple/character3.png">
<h4>We're all shorter images</h4>
<img src="https://dl.dropboxusercontent.com/u/139992952/multple/fb.png">
<img src="https://dl.dropboxusercontent.com/u/139992952/multple/car1.png">
<img src="https://dl.dropboxusercontent.com/u/139992952/multple/ball1.png">


2
找到了一个纯CSS的解决方案,我会发布出来。感谢您的回复。为您的努力点赞! :) - Steve

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接