我即将为一个新的小元素编写一些模板 - 我只是想知道一件事:
如果我希望我的整个页面内容都在一个居中的列中,比如 - 800px 宽度,通常的做法是这样(至少,这是我一直这样做的方式):
<html>
<head>
<style>
body {
text-align: center; /* IE6 */
}
#wrapper {
margin: 0px auto;
width: 800px;
background-color: #eee; /* to see it better */
text-align: left; /* IE6 */
}
</style>
</head>
<body>
<div id="wrapper">
... content ...
</div>
</body>
</html>
现在,还有另一种方法可以做完全相同的事情,但使用
margin: -50%;
(或固定值,在本例中为 margin: 400px;
),如下所示:<html>
<head>
<style>
body {
margin-left: 50%;
}
#wrapper {
margin-left: -400px;
width: 800px;
background-color: #eee; /* to see it better */
}
</style>
</head>
<body>
<div id="wrapper">
... content ...
</div>
</body>
</html>
我的问题是 - 这两种方法中的一种比另一种有什么优势吗?还是缺点?是否有一个常见的“最佳解决方案”来使主列居中?
最佳答案
margin:0 auto;
将确保元素两侧有相等的空间。margin-left:50%;
是相对于父级的。例如,如果容器的宽度为 1000 像素,则子元素上的左边距为 500 像素。但是,这不会使元素居中,而是将其左侧放在中间 - 除非您像示例中那样在子元素上使用固定值对其进行修改。
通常,当您像您的情况一样处理包装器时,margin:0 auto;
是最简单和最灵活的解决方案。在其他情况下,您可能会发现使用百分比或固定值更好(例如,在 float 内容时)。
关于html - margin : 0px auto VS margin: -50%,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10893647/