CSS code to center a div horizontally and vertically

« Go back

Centering a div Horizontally and Vertically

Centering a div horizontally

HTML
<div class="outerDiv">
<div class="innerDiv">
		<!-- HTML code goes here -->
		#</div>
<!-- .innerDiv --></div>
<!-- .outerDiv -->
CSS
.outerDiv { overflow:hidden;}
.innerDiv { margin:0 auto;
			width: 50%; /* adjust width to suit your needs */
			}

Centering a div vertically

HTML
<div class="outerDiv">
<div class="innerDiv">
		<!-- HTML code goes here -->
		#</div>
<!-- .innerDiv --></div>
<!-- .outerDiv -->
CSS
.outerDiv { position:relative;
			height:300px; /* Set fixed height value */
			width:300px; /* Set fixed width value */
			border:1px solid red;
			}
.innerDiv { position:absolute; top:50%;
			height:100px; /* Set fixed height value */
			margin-top:-50px; /* Top margin is half the height */
			border:1px solid green;
			}
Source: http://phrogz.net/css/vertical-align/index.html
Share and Enjoy:
  • Facebook
  • Twitter
  • Reddit
  • StumbleUpon
  • Digg

Tags: ,

About the author

Author

I started my career as a print designer and wanted nothing to do with "code". Then slowly I began to learn by reading tutorials online. My learning process has been challenging, yet very rewarding. My goal is to document the lessons I have learned and to encourage other beginners in the field of web design / front-end programming. - Jacob Lett