Your source for everything web
14 Apr
How do I center a CSS Div Horizontally? This is a question I hear from my readers in both emails, and comments somewhat frequently. There are already at least 10 (probably more like 100) other websites that tell you how to do this, but the question still comes up.
So being that I am such a nice guy, I figured I would write a blog post about the subject instead of just answering emails, and comments all day.
The code to center a div horizontally is really simple. It should be noted that you MUST have a fixed width div for this to work.
#div-container {
width:800px;
margin: 0 auto;
}
The margin CSS values I used above were written in CSS Shorthand, but you could also write the code without shorthand, in which case the code would look like this:
#div-container {
width:800px;
margin: 0 auto 0 auto;
}
Now just insert a DIV into your html with the IDÂ given a value of div-container like is shown in the example below.
<div id=”div-container”>
Place your newly centered div’s content here
</div>
So that’s the long and short of it. Pretty simple and upfront. Hopefully I won’t get any more emails about this, but as always feel free to email or comment if you have any questions or comments.