1

How to make div horizontally and vertically centered without scripting? Only on CSS and HTML5?

<div id="center"></div>

#center{width:500px; height:300px;}
Ilya Medvedev
  • 1,281
  • 3
  • 12
  • 22

4 Answers4

2

For fixed size :

#center{
    width:500px;
    height:300px;
    position:absolute;
    top:50%;
    left:50%;
    margin:-150px 0 0 -250px;
}

If you want to resize your div with the screen you can use this technique which works for div too.

MatTheCat
  • 18,071
  • 6
  • 54
  • 69
1

Have you tried CSS 3 box-align?

#center {
    box-align: center;
}

Find more information here: http://hacks.mozilla.org/2010/04/the-css-3-flexible-box-model/

treppo
  • 547
  • 4
  • 17
  • maybe you need to add the vendor specific prefixes: *-moz-box-align: center;* for Firefox or *-webkit-box-align: center;* for Safari & Chrome – treppo Aug 24 '11 at 09:44
  • If you don't want to use cutting-edge CSS 3 syntax you could have a look at http://blog.themeforest.net/tutorials/vertical-centering-with-css/ – treppo Aug 24 '11 at 09:50
1
body, html {height:100%}
.mydiv {width:300px; height:300px; margin:auto; background:#FF0000}
<table width="100%" border="0" cellspacing="0" cellpadding="0" height="100%">
  <tr>
    <td align="center" valign="middle"><div class="mydiv"></div></td>
  </tr>
</table>
0

just Add this things: margin-left: auto ; margin-right: auto ;

so, Your center should be like this:

#center
{width:500px;
 height:300px;
 margin-left: auto ;
 margin-right: auto ;
}
Mahesh Thumar
  • 4,257
  • 5
  • 22
  • 30