Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center an auto-width div?

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?

like image 642
Dan K Avatar asked Aug 30 '13 04:08

Dan K


People also ask

How do I center div auto width?

To center a div horizontally on a page, simply set the width of the element and the margin property to auto. That way, the div will take up whatever width is specified in the CSS and the browser will ensure the remaining space is split equally between the two margins.

How do I center a div with margin auto?

To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.

How do I force a div to center?

Simply add text-align center to parent div and set the child div display to inline-block. This will force our div to behave like inline element and therefore subjected text-align center.

How do I center a div inside another div?

To move the inner div container to the centre of the parent div we have to use the margin property of style attribute. We can adjust the space around any HTML element by this margin property just by providing desired values to it. Now here comes the role of this property in adjusting the inner div.


1 Answers

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

like image 121
zloctb Avatar answered Sep 23 '22 19:09

zloctb