简体   繁体   中英

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 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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM