父容器中的中心图像

时间:2015-04-21 01:31:09

标签: javascript css css3 flexbox centering

想要在垂直和水平方向上居中图像,而无需在父母身上明确设置高度。我希望最高图像的高度是父母的高度,并将所有其他兄弟图像置于中心。

最终结果将显示为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>

1 个答案:

答案 0 :(得分:2)

如果您希望将所有容器的大小调整为最高的图像,则必须设置容器div大小...

您可以使用javascript将所有Flexbox容器div的大小设置为最大高度&amp;你的图像宽度。

然后使用flexbox通过在容器上设置justify-content:centeralign-items:center来使图像居中。

enter image description here

示例代码和演示:

$(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">