0

What's the best way to center using CSS?

<div style="position: absolute; left: 50%;">
    <div style="position: relative; left: -50%">
        Centered content
    </div>
</div>

or just

    <div style="text-align:center">
        Centered content
    </div>

?

Edit: ok, so I should use "text-align:center" for inline elements and "margin: 0 auto" for block elemtns Thank you.

4

4 回答 4

4

First one is gnarly, don't see something like that much, text-align:center is quite reliable for inline elements but when an element won't center margin: 0 auto; my is my old standby.

<div style="text-align:center">
        Centered content
</div>

or

<div style="margin: 0 auto;">
        Centered content
</div>

And like BenM said, margin: 0 auto; centers display:block elements that have a defined width.

So what is margin: 0 auto; doing? Well 0 sets the top and bottom margin to be 0 and auto tells the browser to calculate the the left and right margin and the browser will do so by assigning equal values to the left and right margin of any element with the margin: 0 auto; style.

于 2013-11-14T22:02:47.697 回答
3

最有效的方法是给元素一个宽度,然后指定margin: 0 auto.

例如:

div {
    width: 900px;
    margin: 0 auto;
}
于 2013-11-14T22:03:13.253 回答
2

如果你是居中inline元素,你应该text-align:center在父元素上使用

如果是block元素 - 使用margin: 0 auto;

 p {
      text-align:center;
 }


 div { 
     width: 100px;
     margin:0 auto;
 }
于 2013-11-14T22:03:16.710 回答
1

文本对齐:居中;只会将 div 元素内的文本居中。要使整个块元素居中,您需要添加边距:0 auto; 或将其定位为 position: absolute/relative,具体取决于您喜欢如何居中(父元素/主体等)

于 2013-11-14T22:15:12.113 回答