Search code examples
csshtmlpositioningalignment

CSS Advanced Div Positioning. Center & Middle


I want to position a <div>

  • To Center with w.r.t body width
  • To Middle with w.r.t body height

The div will have these properties:

  • width of div will be 90%
  • height of div auto, min. will be known

Solution

  • I've tested this in IE8, Firefox, Chrome. It does not work in IE7.

    If you need this to work in <= IE7, I imagine the simplest solution would be to give up on pure CSS and use javascript for the vertical positioning.

    Live Demo

    HTML:

    <div id="container"> 
        <div id="content"> 
            <input type="button" value="click me" onclick="javascript:document.getElementById('content').innerHTML += 'i i i i i i i i i i i i i i i i i i i i i i i i i<br />';" /><br />
            i i i i i i i i i i i i i i i i i i i i i i i i i<br />
            i i i i i i i i i i i i i i i i i i i i i i i i i<br />
            i i i i i i i i i i i i i i i i i i i i i i i i i<br />
            i i i i i i i i i i i i i i i i i i i i i i i i i<br />
        </div> 
    </div>
    

    CSS:

    html, body {
     margin: 0;
     padding: 0;
     border: 0;
    
     width: 100%;
     height: 100%
    }
    
    body {
     display: table
    }
    
    #container {
     width: 100%;
     display: table-cell;
     vertical-align: middle
    }
    
    #content {
     background: red;
     width: 90%;
     margin: 0 auto;
     min-height: 150px
    }