0

I want to center a DIV which width is unknown. It should be as width as the actual content. I tried:

<div style="background-color: red; width: 300px; text-align: center; margin: 0 auto;">dsffsffsfsddf</div>

it only works when "width" is set. Auto wont help.

John Smith
  • 6,129
  • 12
  • 68
  • 123
  • 2
    I don't understand. If the width is unknown, then being a block element the width is 100% and centering is irrelevant. If the width is being set somehow, then `margin:0 auto` works fine. – j08691 Nov 03 '13 at 20:06

5 Answers5

1

display: table; margin: 0 auto;

http://jsfiddle.net/vabxz/

reepee
  • 154
  • 3
  • Please provide a little more context for the person who asked. – Evan Nov 03 '13 at 20:29
  • Works in all browsers except ≤ IE7, so it should be good. But if you need IE7 then the only way is http://jsfiddle.net/w6UcB/ like JasonB mentioned, but it requires extra markup. – reepee Nov 04 '13 at 00:57
1
div{
    display:table
    margin:0 auto;
}
ggdx
  • 3,024
  • 4
  • 32
  • 48
1

Take a look at this previous answer: centering variable width divs

But one answer is to basically use css-floats

<style type="text/css">
#hideoverflow { overflow: hidden; }
#outer { position: relative; left: 50%; float: left; }
#inner { position: relative; left: -50%; float: left; }
</style>

<div id="hideoverflow">
    <div id="outer">
        <div id="inner">
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed id velit vel  augue fringilla rhoncus at et odio. Suspendisse potenti. Aliquam justo  libero, commodo ut iaculis in, placerat vel purus.
        </div>
    </div>
</div>
Community
  • 1
  • 1
JasonB
  • 899
  • 5
  • 5
  • As Xeepete points out, this is the belt and braces approach for browsers down to IE7. If you don't need to go that far, use the display : table; as mentioned in the accepted answer. – JasonB Nov 04 '13 at 10:18
1

It's quite simple (http://jsfiddle.net/bukfixart/tYyJN/):

<div style="border:1px solid #000;text-align:center;">
    <div style="border: 1px solid #f00; display:inline-block;">some content</div>
</div>

The key points are text-align:center for the outer box and display:inline-block for the inner box

bukart
  • 4,906
  • 2
  • 21
  • 40
1

Check out my fiddle: http://jsfiddle.net/PRUBd/

CSS

body {
    text-align: center;
}

#container {
    text-align: left;
    border: 1px solid black;
    padding: 10px;
    display: inline-block;
}

HTML

<div id="container">
   This div is as wide as its content and centered!
</div>

enter image description here

Charles Ingalls
  • 4,521
  • 5
  • 25
  • 33