CSS: centering a div of unknown width

I have a <div> that contains some dynamically generated content. If I knew its width, I could center it like this:

<div style=“border: 1px solid black; width: 600px; margin-left: auto; margin-right: auto;”>

However, I want it to resize itself to the width of its content.

I can do this by adding “float: left;” to the style attribute, but this causes “margin-left: auto; margin-right: auto;” to stop working.

Is there any way to get both the centering and the auto-sizing?

Thanks in advance.

What’s the dynamically generated content? Just text?

You could wrap that content in another div, set it’s width as auto, then set 50% margins (left and right) to it. That’d be my first attempt at solving it.

Also, the best place I have found on the net to ask these types of questions is the Web Developer Forum. It’s a reasonably busy place, and you’ll notice that CSS has its own dedicated message board. To give an idea of traffic, there’s currently 69 people viewing the CSS forum.

Also try Dynamic Drive, there forums are full of people that will actually help you, plus there are lots of pre-made scripts and you can look at the coding of these and see what you need

CSS Centering 101.

Works like a charm.

Oh, and put your CSS in a style sheet and not inline.

Thank you all for the suggestions. I don’t think any of them quite solve my problem, but I will also post to the other boards you mention.

Adding “style=‘width: auto’” doesn’t seem to do anything for me. I can only get it to auto-size by making the div float, which breaks my auto-centering.

I tried that, but it only seems to work if the width of the container div is specified. I want it to automatically resize to its contents (like it does if I add “float: left”).

I had what I think is the same problem as you (well, I wanted it centered vertically as well as horizontally). I’m not much of a designer and was frustrated at not being able to find a simple solution that worked consistently.

Here is what finally worked for me and didn’t involve like a 10 meg .css:

http://www.sitecrafting.com/blog/to-center-div/

Do you have some code, or a link to share? It’s easier to offer help if you have something to share.