绝对定位+负边距随着窗口大小的调整而失真



我有一个包装器div,我希望它位于窗口的中心。我使用了以下CSS来实现这一点:

#wrapper {
    width: 960px;
    margin-left: -480px;
    position: absolute;
    left: 50%;
}

唯一的问题是,当我改变浏览窗口的大小时,我看不到窗口中点的任何剩余部分。我知道这是因为负利润,但有什么方法可以纠正吗?

我正试图将其浮动在其他一些div上,因此自动边距技巧将不起作用。

这是我的链接:dev.connectionsquad.com.

我建议对页面中心的任何div执行以下操作。body { text-align: center; } #wrapper { width: 1080px; margin: 0px auto; text-align: left; }

对于某些浏览器,您必须在body标记上使用text-align:center来使div在页面中居中。

我建议重写代码并使其符合标准,如下所示:

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8" />
    <title></title>
    <style type="text/css">
html, body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    min-height: 600px;
}
body {
    background: #222;
    text-align: center
}
#content {
    text-align: left;
    display: inline-block;
    position: absolute;
    width: 40%;
    min-width: 300px;
    height: 50%;
    min-height: 400px;
    top: 10%;
    margin-left: -20%;
    padding: 25px;
    background-color: #ccc;
    background-image: url('/img/noise.png');
    border: 5px solid #000
}
#background {
    position: absolute;
    width: 100%;
    height: 250px;
    top: 50%;
    margin-top: -125px;
    z-index: -1;
    background-color: #666;
    background-image: url('/img/placeholder.png');
    border-top: 5px solid #eee;
    border-bottom: 5px solid #eee;
}
a:active, a:visited {
    color: #075f76
}
    </style>
</head>
<body>
    <div id="content">
        <h1>Test</h1>
    </div>
    <div id="background"></div>
</body>
</html>

请参阅HTML5-MDN。

最新更新