Tuesday, November 29, 2011

Centering an inner div vertically inside another div

Green div is centered on a gray div
So how do you:
A div tagged as "divsmall" is contained inside a bigger div tagged as "divbig". the challenge is how to *vertically* align/center divsmall inside divbig.
Interesting question although having limited applications but still this should be possible. So, broke out my favorite IDE and started coding away. We start with our HTML.

 <!DOCTYPE html>  
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
     <link rel="stylesheet" type="text/css" href="css/mystyle.css"/>  
     <div class="div-big">  
       <div class="div-small">  
This should be easy to read. We then move to the CSS.

    background: #999;
    border: 1px solid #000;
    min-height: 640px;
    margin: auto;
    text-align: center;
    width: 940px;

    background: #66cc00;
    border: 1px solid #666;
    min-height: 600px;
    margin: 20px auto;
    width: 25%;
The trick in the margins. If you look at line 14, that all you need to center inner div. The width doesn't really matter. Try modifying the width value at line 15. The div should adjust in relation to its parent div.