Center an auto-width div?

Dan K picture Dan K · Aug 30, 2013 · Viewed 57.7k times · Source

I'm having trouble because I have a div I want to center and what I have usually been told to do is this:

width: 700px;
margin-left: auto;
margin-right: auto;

the trouble is, this is for if you want the div to be a fixed width. I want the div to adjust its size based on the text in the div, and still be centered. I tried:

width: auto;
margin-left: auto;
margin-right: auto;

but this didn't work. It stretches the div to fill up the screen when I do this.

Anyone know what to do here?

Answer

zloctb picture zloctb · Aug 30, 2013

for parent block or body - text-align:center; for centerd block- display:inline-block;

.center{display:inline-block;background:red}
body{text-align:center}

<div class="center">
    <p contenteditable="true">write text</p>
</div>

DEMO http://jsfiddle.net/RXP4F/

Content Editable MDN