【问题标题】:Center Images inside Parent container在父容器中居中图像
【发布时间】:2015-06-27 23:18:29
【问题描述】:

想要将图像垂直和水平居中而不明确设置其父级的高度。我希望最高图像的高度是父图像的高度,并将所有其他同级图像居中。

最终结果将类似于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>

【问题讨论】:

标签: javascript css flexbox centering


【解决方案1】:

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

您可以使用 javascript 将所有 flexbox 容器 div 的大小设置为图像集的最大高度和宽度。

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

示例代码和演示:

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

【讨论】:

  • 找到了一个纯 css 解决方案,我将发布。谢谢您的答复。为努力点赞! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-31
  • 2012-07-01
  • 2015-03-16
  • 2013-08-28
  • 1970-01-01
  • 2015-07-19
相关资源
最近更新 更多