想要在垂直和水平方向居中图像而不明确设置其父项的高度。我希望最高图像的高度是父图像的高度,并将所有其他同级图像居中。
最终结果将类似于 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:center
和 align-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">
关于javascript - 在父容器中居中图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29761314/