Monday, October 21, 2013

CSS magic: Keeping a larger div centered inside a smaller one

I needed to put a HD width slider on a page and had to keep it centered even on smaller screens. Basically I had to keep a larger div centered inside a smaller div.

My first try caused the slider to stick to the left on smaller screens, so I had to dig for a solution.

The html markup is something like this:

 <div id="start-slider-wrap">  
      <div id="start-slider">  
           <?php  
                if ( function_exists('easingsliderpro') ) { easingsliderpro( 2 ); }  
           ?>  
      </div>  
 </div>  

The CSS needed for the desired effect is this:

 #start-slider-wrap {  
      width: 100%;  
      height: 815px;  
      overflow: hidden;  
      position: relative;  
 }  
 #start-slider {  
      width: 1920px;  
      height: 815px;  
      position : absolute;  
      left: 50%;  
      top: 50%;  
      -webkit-transform: translate(-50%, -50%);  
      -moz-transform: translate(-50%, -50%);  
      -ms-transform: translate(-50%, -50%);  
      transform: translate(-50%, -50%);  
 }  

This works in all modern browsers with and IE 9+ too. The content is centered both horizontally and vertically, though vertically centering is not needed on the live side - it can be ommitted.

For IE versions below 9 I had a seperate css file that made the slider acceptable, though sticking to the left side:

 #start-slider {  
   left: 0;  
   top: 0;  
 }