I\'m trying to center two divs with dynamic heights inside a dynamic wrapper... I\'ve been playing with all sorts of tricks to try and get this working cross-browser to no a
Use display: inline-block
+ vertical-align: middle
on the blocks, so they would be aligned just like you want them to.
Look at this example: http://jsfiddle.net/kizu/Tky8T/
Even more: the height of the red div can be dynamic too!
So I've had a quick poke at your question, it's not a very big jQuery solution, in fact it's so simple that even i could do it !
What i did was worked out which div is bigger dynamically (i.e. is red or green bigger), we then ignore the bigger div and work out the correct vertical margin for the smaller div.
View this example for a better understanding: http://jsfiddle.net/6fN48/
#wrapper
{ width: 400px; border: 1px solid blue; padding: 10px; margin: 0 auto; }
#wrapper .red
{ width: 195px; float: left; border: 1px solid red; }
#wrapper .green
{ width: 195px; float: right; border: 1px solid green; }
var r = $('#wrapper .red').outerHeight();
var g = $('#wrapper .green').outerHeight();
var w = $('#wrapper').outerHeight();
/* calculate which is bigger and apply the margin to that element */
/* is the red or green div bigger? */
if(r > g){
/* ok red is bigger, then work out the top margin to apply onto green */
var x = (w - g) / 2;
/* apply CSS to the green div */
$('#wrapper .green').css({ 'margin-top' : x + 'px' });
} else if(r < g){
/* ok green is bigger, then work out the top margin to apply onto red*/
var x = (w - r) / 2;
/* apply CSS to the red div */
$('#wrapper .red').css({ 'margin-top' : x + 'px' });
}
<div id="wrapper">
<div class="red">
Lorem ....
</div>
<div class="green">
Lorem ipsum dolor ...
</div>
<br clear="all" />
</div>
I hope this helps, the only other way is to use css positioning with a known height, which obviously is not dynamic. :)
Why don't use flex?
.wrapper {
height: 200px;
position: relative;
}
.green {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
height: 100%;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
}
If you make the wrapper div
to be posititon: relative
. Then have the green div
to be position: absolute
, you can make it vertically centered. Here is an example: http://jsfiddle.net/56Ase/