Alex Zhukovskiy
Alex Zhukovskiy

Reputation: 10025

Center div using margin 0 auto

I learned several examples on the internet, but obviously i'm missing something, because my markup is not working.

AFAIK this coude should work, but it doesn't. Why?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <body style="background: #cdc7ae" class=" ms-backgroundImage" spellcheck="false">           
        <div style="margin: 20px auto;">Hello!</div>    
    </body>
</html>

Upvotes: 0

Views: 179

Answers (3)

user3351229
user3351229

Reputation: 105

You must give a width to your div. Otherwise, it assume 100% width and margin:auto does not take effect.

Upvotes: -1

Ruddy
Ruddy

Reputation: 9923

So turns out you are looking for:

<div style="margin: 20px auto; text-align: center;">Hello!</div> 

Without setting a div width it will be 100%, so we can use text-align: center to get the text in the center. No need to move the whole div by setting a width in this case.

DEMO HERE

Upvotes: 2

Taimur
Taimur

Reputation: 3241

You need to specify a width on the <div>, e.g.

<div style="margin: 20px auto; width: 200px">Hello!</div> 

Upvotes: 4

Related Questions