javascript - 在父容器中居中图像

标签 javascript css 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>

最佳答案

如果您希望所有容器的大小都适合最高的图像,则必须设置容器的 div 大小...

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

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

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

关于javascript - 在父容器中居中图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29761314/

相关文章:

php - jquery 数据表自动换行不起作用

html - 使输入字段在长类型上增长

html - 响应式 CSS 适用于常规浏览器,不适用于移动设备……为什么?

html - Safari 6 (iOS 6) flex 布局不换行元素

javascript - 如何将 html 文件加载到 jquery 选项卡中

javascript - 鼠标悬停事件未在某些子元素上触发

javascript - Flexbox:一旦另一个 flex 元素的宽度为 0,如何包装一个 flex 元素?

CSS flex 盒 : How do I resize a fixed size image while retaining the aspect ratio

css - Firefox 上具有百分比宽度的 Flexbox 无法正常工作

javascript - 我必须遍历多级 JSON 并删除某些键