Want to center images both vertically and horizontally without explicitly setting a height on their parents. I would like the height of the tallest image to be the height of the parent and center all other sibling images.
The final results will look like http://fiddle.jshell.net/4myos5s2/ where the tall image sets the height of the parent.
Using flexbox but still requires defining height for parent: 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>
If you want all the containers to be sized to the tallest image, you must set the container div sizes...
You can use javascript to set the size all your flexbox container divs to the maximum height & width of your set of images.
Then use flexbox to center the images by setting justify-content:center
and align-items:center
on the container.
Example code and a Demo:
$(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">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With