Ste*_*eve 5 javascript css centering flexbox
想要垂直和水平居中图像,而无需明确设置其父级的高度。我希望最高图像的高度是父图像的高度,并将所有其他兄弟图像居中。
最终结果将类似于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>
Run Code Online (Sandbox Code Playgroud)
如果您希望所有容器的大小都调整为最高的图像,则必须设置容器 div 大小...
您可以使用 javascript 将所有 Flexbox 容器 div 的大小设置为图像集的最大高度和宽度。
然后使用 Flexbox 通过在容器上设置justify-content:center和来使图像居中。align-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(){});Run Code Online (Sandbox Code Playgroud)
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;
}Run Code Online (Sandbox Code Playgroud)
<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">Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1770 次 |
| 最近记录: |