这个CSS代码是如何在网页中居中的?

这个CSS代码是如何在网页中居中的?,css,Css,这个CSS代码是如何在网页中居中的 html, body { margin:0; padding:0; color:#000; background:#fff; } #body { width:870px; margin:0 auto; background:#ddd; } 将任何块居中 但这不是居中的主体,只是一个id为“body”(我觉得有点误导)的div。没有什么问题 body{…}指的是整个页面,即文档的正文 #body{…}肯定

这个CSS代码是如何在网页中居中的

html,
body {
    margin:0;
    padding:0;
    color:#000;
    background:#fff;
}
#body {
    width:870px;
    margin:0 auto;
    background:#ddd;
}
将任何块居中


但这不是居中的
主体,只是一个id为“body”(我觉得有点误导)的
div

没有什么问题

body{…}
指的是整个页面,即文档的正文


#body{…}
肯定是身体中带有
ID=“body”
的div。CSS是正确的,因为它在左侧和右侧提供了固定的宽度和自动边距。

在将类或ID命名为body/head/footer/等时要小心。您发布的代码可以正常工作,因为
margin:auto
将使块居中,但该命名方案很容易导致意外更改。尝试使用
#wrapper
#container
或类似的工具。

这在现代浏览器中可以使用,但您需要添加更多属性才能在旧版本的IE中使用

html,
body {
    margin:0;
    padding:0;
    color:#000;
    background:#fff;
    text-align:center; /* align contents to center which will align #body center */

}
#body {
    width:870px;
    margin:0 auto;
    background:#ddd;
    text-align:left; /* re-arranges contents of #body to default left */
}

但是需要注意的是,
margin:auto
转换为
margintop:auto;左边距:自动;页边距底部:自动;右边距:自动,但只有左右边距会导致居中行为。(也就是说,div没有垂直居中。
页边距顶部:auto
页边距底部:auto
被有效忽略。)+1提及
元素可能出现的命名混乱。
html,
body {
    margin:0;
    padding:0;
    color:#000;
    background:#fff;
    text-align:center; /* align contents to center which will align #body center */

}
#body {
    width:870px;
    margin:0 auto;
    background:#ddd;
    text-align:left; /* re-arranges contents of #body to default left */
}