Centering A Div – Quick Reference Guide

I have been designing web pages using CSS for years now I have to admit, I still have to regularly look up how to center a div. It seems simple enough (maybe I am too used to the old HTML <center> tags), but I as am constantly struggling with it I decided to write a quick reference guide.

Center a Relatively Positioned Div

.centeredDiv {
width: 500 px;
margin-left: auto;
margin-right: auto;
}

Note: You must set a width for this to work

Center Absolutely Positioned Div

.centeredDiv {
width: 100px;
left: 50%;
margin-left: -50px; /*half of the width*/
}

Note: This will center the div relative to the first parent element that is not positioned static or the <html> block if no element is found.

As I was figuring all this out (again) to write it down, I think I am realizing the reason why I always seem to get it wrong. You have to employ different strategies depending on whether or not the element you are trying to center is absolutely position or relatively positioned.

 

Source: http://www.thesitewizard.com/css/center-div-block.shtml
Source: http://www.sitepoint.com/css-center-position-absolute-div/
Source: http://www.w3schools.com/css/css_positioning.asp

Comments are closed.