保证金:0px自动VS保证金:-50%

Kat*_*tai 3 html css centering

我即将为一个新的小项目编写一些模板 - 我只是想知道一件事:

如果我希望我的整个页面内容都在一个居中的列中,让我们说 - 宽度为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>
Run Code Online (Sandbox Code Playgroud)

现在,有另一种方法可以做同样的事情,但是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>
Run Code Online (Sandbox Code Playgroud)

我的问题是 - 这两种方法中的一种是否比其他方法有任何优势?还是有缺点?是否有一个共同的"最佳解决方案"来集中主列?

Nix*_*Nix 7

margin:0 auto; 将确保元素两侧有相等的空间.

margin-left:50%;是相对于父母.例如,如果容器宽度为1000px,则子元素的左边距为500px.但是,这不会使元素居中,它会将其左侧放在中间 - 除非您在子元素上使用固定值进行破解,如示例所示.

通常,当您在处理包装器时,就像您的情况一样,margin:0 auto;是最简单,最灵活的解决方案.在其他情况下,您可能会发现使用百分比或固定值更好(例如,浮动时).