user366312
user366312

Reputation: 17026

CSS - centering the DIV content, not DIV itself

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.

Upvotes: 0

Views: 1080

Answers (2)

xentek
xentek

Reputation: 2645

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.

Upvotes: 0

Sam Becker
Sam Becker

Reputation: 19646

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 */
}

Upvotes: 3

Related Questions