How can I center something if I don't know ahead of time what the width is?

后端 未结 8 1844
生来不讨喜
生来不讨喜 2021-01-06 08:02

I am trying to center a paragraph tag with some text in it within a div, but I can\'t seem to center it using margin: 0 auto without having to specify a fixed width for the

8条回答
  •  北荒
    北荒 (楼主)
    2021-01-06 08:45

    Eh, auto margins need set width since by default block-level element, such as

    would expand onto whole available width.

    If you're not supporting IE < 8 you could just set { display: table; margin: 0 auto; }

    Otherwise, if your element is surrounded by block-level elements, you could do p { display: inline-block; } p { display: inline; } html > /**/ body p { display: inline-block; } (last two rules are for IE and resetting IE fix for sane browsers) after that, apply { text-align: center; } on the container.

    As someone mentioned already, see http://haslayout.net/css-tuts/Horizontal-Centering for more info.

    Cheers! Zoffix Znet

提交回复
热议问题