【问题标题】:margin auto not centering content边距自动不居中内容
【发布时间】:2014-06-07 07:50:17
【问题描述】:

您好,我遇到了简单 CSS 的问题。我试图通过使用 margin-right: auto 和 margin-left: auto 使我的 div 标签居中在我的页面上,但它似乎并没有使内容居中。我一直在寻找答案,但我找不到最简单的代码有什么问题。

<html>
<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<style type="text/css">
body {
    margin-left: 0px;
    margin-right: 0px;
    margin-top: 0px;
    margin-bottom: 0px;
}

#container {
    font-family: Georgia, "Times New Roman", Times, serif;
    background-color: #666;
    height: auto;
    width: 800px;
    margin-top: 0px;
    margin-right: auto;
    margin-left: auto;
}
</style>
</head>
<body>

<div id="container">
Hello world!
</div>

</body>
</html>

【问题讨论】:

  • div 以我为中心。然而,里面的文字不是。
  • 我的浏览器渲染我的 css 一定有问题。谢谢j
  • 您使用什么浏览器?不是IE吗?如果没有 doctype,任何 IE 都会将页面呈现为 IE5,不支持以 margin:auto 居中。

标签: css html containers center margin


【解决方案1】:

display:table 添加到您的#container

#container {
    font-family: Georgia, "Times New Roman", Times, serif;
    background-color: #666;
    height: auto;
    width: 800px;
    margin-top: 0px;
    margin-right: auto;
    margin-left: auto;
    display:table;
}

【讨论】:

    【解决方案2】:

    它可能不以你为中心的唯一原因是你没有

    <DOCTYPE html>
    

    等页面加载相当于ie5,不支持

    margin: 0 auto;
    

    【讨论】: