Centering a DIV Horizontally

Sharing is Caring

Assuming you have a basic knowledge of css and html putting a div in the horizontal center of a containing block isn’t too difficult. I’m going to center a div with only text, but the exact same css may be used for a div containing images,inputs, etc. I’m going to assume you are using html or xhtml strict and have a div that has the following code:


<div id="toBeCentered">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat</div>

All new web designers and developers assume that the css can simply be text-align:center; , but this isn’t correct because this centers the contents of the box instead of the box itself.

#toBeCentered {
text-align:center;
}

To make the div center horizontally we need to ensure we do two things:

      Set a width to the div
      Set the left & right margins to auto. Web browsers are required to give the margins equal width which will set the div exactly in the center. works width.

We must instead change the css to auto the left and right margins and must set a size to the div. Setting a size to the div

#toBeCentered {
width: 200px;
margin-left: auto;
margin-right:auto;
}

Hope this helps!

Sharing is Caring

Brian is a programmer and technology leader living in Niagara Falls with more than ten years of development experience. He is passionate about automation, business process re-engineering, and building a better tomorrow.

Brian is a proud father of four: two boys, and two girls and has been happily married to Crystal for more than ten years. From time to time, Brian may post about his faith, his family, and definitely about technology.

3 Comments

Comments are closed.