Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically centering multiple div's in its parent div

Tags:

html

css

I have a set of elements inside a parent element. The parent element's height can change (it will be changed by some jQuery files). Here is how the layout looks:

 <div class = "parent">
     <div class="child1">
     </div>
     <div class="child2">
     </div> 
 </div>

I want the child elements to end up aligned at the middle of the parent div, but i can't figure out how to write the css to do so. I have tried writing things like:

 .child1 {
        ...
       vertical-align: middle;
 }

Which doesn't work. I have also tried:

 .parent {
       display:table;
 }
 .child1 {
       display:table-cell;
       vertical-align:middle;
 }

This also doesn't work. Any ideas how to do this?

like image 954
jay Avatar asked Mar 08 '12 19:03

jay


2 Answers

You can create a wrapper for the elements you wish to center inside a container that gets centered instead like so:

HTML

 <div class ="parent">
     <div class="centerme">
        <div class="child1">
           ....
        </div>
        <div class="child2">
           ....
        </div>
      </div>
 </div>

Then you can simply do this:

CSS

.block:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -0.25em; /* Adjusts for spacing */
 }

Demo. Method found over at CSS-tricks.

like image 86
Andres Ilich Avatar answered Sep 28 '22 01:09

Andres Ilich


Check this link : http://www.jakpsatweb.cz/css/css-vertical-center-solution.html

this will bring your child div's top to 50% of the container. just add margin-top: -(x)px; where (x) is half of your child div's height.

like image 44
Arsh Singh Avatar answered Sep 28 '22 00:09

Arsh Singh