I have a block-level element of unknown width. This element needs to be horizontally centered on the page, and its position needs to be relative so that its absolutely positioned child will show up in the right place. You can see it in action here.
As far as I know, the best way to center an element of unknown width is to set its display to table. Semantically, this seems incorrect, because my element has nothing in common with a real table. Even worse, Firefox doesn’t apply position to tables, so the absolutely positioned child shows up in the wrong spot:

Are there any workarounds for this that:
- don’t add any extra elements to the html
- don’t calculate and set the element’s width with JavaScript
I’d like a pure CSS fix, and I’m running out of ideas…
Adding
display: inline-block;to the element (#box) should suffice. This will cause it to become an inline element and still keep its “boxy” properties. Its width will automatically take up the width of its children.Then you can set its alignment by setting
text-align: center;on its parent.IE7 does not support this
displayvalue (only on naturally inline elements), but the situation is the same withtable(no support at all). You can use a hack though to makeinline-blockwork in IE7.jsFiddle Demo