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>  
 <html>  
   <head>  
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
     <link rel="stylesheet" type="text/css" href="css/mystyle.css"/>  
     <title></title>  
   </head>  
   <body>  
     <div class="div-big">  
       <div class="div-small">  
         <strong>div-small</strong>  
       </div>  
     </div>  
   </body>  
 </html>  
This should be easy to read. We then move to the CSS.

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

.div-small{
    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.

No comments:

Post a Comment