Center a relatively positioned element with unknown width in Firefox
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 positi开发者_JAVA百科oned 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 display
value (only on naturally inline elements), but the situation is the same with table
(no support at all). You can use a hack though to make inline-block
work in IE7.
jsFiddle Demo
If worst comes to worst, you could try text-align: -moz-center;
which is a Firefox-specific method of centering block elements like inline-elements.
精彩评论