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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With