2015-04-21 18 views
4

想要在垂直和水平方向上居中放置圖像,而無需在父母上明確設置高度。我希望最高的圖像的高度是父母的高度,並居中所有其他兄弟姐妹圖像。父容器中的中心圖像

最終結果看起來像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

嘗試這種解決方案; http://stackoverflow.com/questions/18516317/vertically-align-an-image-inside-a-div-with-responsive-height – user1012181

+1

@ user1012181謝謝!該解決方案有效。我會把它作爲答案。 – Steve

回答

2

如果你想所有容器的大小,以最高的圖像,你必須設置div容器的大小...

您可以使用JavaScript來設置大小所有Flexbox的div容器到您的圖像集的最大高度&寬度。

然後使用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">

+2

找到了我將發佈的純CSS解決方案。感謝您的答覆。 Upvote的努力! :) – Steve