Wednesday, July 10, 2013

How to Center a DIV tag horizontally using CSS

I miss the days of using the CENTER tag. Now it seems it is not really a good idea to use the CENTER tag. It is recommended that CSS be used instead. It seems that it is a bit more difficult to do with CSS.
In this example, my DIV only contains text, but it could contain anything. If it was just text, text-align:center could be used, but to center a div tag and its contents it takes a bit more.

First thing we need to do is give the DIV a width and then it can be centered. Here is an example of how to center a DIV that is 400px wide.


<div style="width:400px; display:block; margin-left:auto; margin-right:auto>">
some stuff here
</div>


You can also create a CSS class and reference it, but I have put the style inline for simplicity, but probably not a good for maintainability.

Thankfully, this is pretty simple once you know what to do.

No comments: