tags:

views:

127

answers:

2

How to center the content in a DIV element (My DIV element may contain an image element or anything.)?

I have used the following code:

div#containerDiv
{
    margin-left: auto ;
    margin-right: auto ;
}

But it is centering the DIV element itself.

I want the content (i.e. image element in the div) to be centered.

The problem with text-align is, it only works horizontally.

+2  A: 

This should do it for you:

div#containerDiv
{
    margin-left: auto ;
    margin-right: auto ;
    text-align: center ;
}

In response to your comment, it's pretty hard to vertically align something the way you want to. I'd recommend something like:

div#containerDiv > img
{
     margin-top: 15px ; 
     /* Where 15 is the amount of space required to center the image */
}
Sam152
text-align:center; centers any inline content, including images and what not.
Sam152
It only works horizontally.
JMSA
There's no equivalent that works vertically. You could use Javascript if needed to set the appropriate top and bottom margins, or make approximate versions of your desires margins like in the above.
Ben
So, this is the bug of CSS!
JMSA
No, it's by design.
Sam152
A: 

If you set the display to 'table-cell' you can sometimes get away with using the vertical-align property. Doesn't work in every browser in every instance, but something to play with.

xentek
Hm, I hadn't considered this, but yeah, support isn't exactly stellar. http://www.quirksmode.org/css/display.html#table
Sam152