tags:

views:

86

answers:

5

I have an outer div that is 800px wide. I have an inner div that could be anywhere from 200 to 600px wide.

I know how to center the inner div within the outer one if I set the inner one to have a specific width, but how do I center it since its a variable width?

Is there a way to set the div to only be the width of the elements inside of it, rather than having it expand to fill its containing div?

+3  A: 

Floating, display:inline-block, or absolute positioning will shrink-wrap a div. Of those, display:inline-block would be the easiest to center with a simple text-align:center. If you have to support crappy browsers (I'm sure you do), check this out.

Assuming you aren't supporting FF2 still, you can actually do away with most of the hacks, and still support older IE's by making the inner div a span instead. display:inline-block works on older IE as long as the element was originally an inline element.

Russell Leggett
A: 

You can dynamically set the X and Y co-ordinates of the innerDIV, whenever you want to re-align the innerDIV. EG:

innerDIV.style.left = (outerDIV.style.width-innerDIV.style.width)/2

innerDIV.style.top = (outerDIV.style.height-innerDIV.style.height)/2

where innerDIV is style is set to position:relative

The Machine
A: 

You can make three css classes with appropriate margin so taht div willl be in center & apply these classes on the basis of width of inner div.

Rahul Malhotra
A: 

Table hate is all the rage these days, but I find that using a table with cells set to percentage widths solves this problem cleanly (and is cross browser):

<table>
  <tr>
    <td width="50%"></td>
    <td>centered content</td>
    <td width="50%"></td>
  </tr>
</table>
Eric Strom
+1  A: 

You will have to set a width on the inner div, otherwise it's implicitly going to take up the whole width of the outer div. If you mean "dynamic width" as in "floated", it'll be really tricky to center it.

So, assuming you do set a width on the div, just add this style:

.centeredDiv {
    width: 400px;
    margin: 0 auto;  // auto left/right margin will center it
}
deceze