中心div使用margin 0 auto

时间:2014-04-16 11:50:42

标签: html css css3 sharepoint margin

我在互联网上学到了几个例子,但显然我错过了一些东西,因为我的标记不起作用。

AFAIK这个coude应该可行,但事实并非如此。为什么呢?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <body style="background: #cdc7ae" class=" ms-backgroundImage" spellcheck="false">           
        <div style="margin: 20px auto;">Hello!</div>    
    </body>
</html>

3 个答案:

答案 0 :(得分:4)

您需要在<div>上指定宽度,例如

<div style="margin: 20px auto; width: 200px">Hello!</div> 

答案 1 :(得分:2)

事实证明你正在寻找:

<div style="margin: 20px auto; text-align: center;">Hello!</div> 

如果不设置div宽度,则为100%,因此我们可以使用text-align: center将文字放在中心。在这种情况下,无需通过设置宽度来移动整个div

DEMO HERE

答案 2 :(得分:-1)

您必须为div提供宽度。否则,它假定100%宽度,margin:auto不生效。