html - Vertically center two divs inside a wrapper (with dynamic content and content below the wrapper)

ID : 274383

viewed : 23

Tags : htmlcsslayouthtml





Top 5 Answer for html - Vertically center two divs inside a wrapper (with dynamic content and content below the wrapper)

vote vote

94

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!

vote vote

90

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/

vote vote

70

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/

CSS

 #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; } 

jQuery

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' });  } 

HTML

<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. :)

vote vote

70

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; } 
vote vote

56

Top 3 video Explaining html - Vertically center two divs inside a wrapper (with dynamic content and content below the wrapper)







Related QUESTION?