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!

Author: Brian Cline

Brian is a programmer living in Niagara Falls with ten years of development experience. He is passionate about automation, business process re-engineering, and gamification. For the last six years or so, he has been working with Salesforce and JavaScript.

Related Posts

Sharing is Caring

3 Responses to “Centering a DIV Horizontally”