【问题标题】:How to make the body (or div) of fixed size stay always in the center of the page (even vertically!)如何使固定大小的正文(或 div)始终保持在页面的中心(甚至垂直!)
【发布时间】:2012-02-03 10:40:44
【问题描述】:

我正在尝试使 1024x768 的主体始终保持在页面的中心(上下间距相同,左右也是)但是我在做这件事时遇到了麻烦。

我使用了 trick 将顶部间距设为 50%,然后我(绝对)将主体定位在 -384px,即 768 的一半。

但是这种方法给我带来了一个问题:如果你的窗口小于 768px,你会得到一个滚动条,但身体上部的一部分被切掉,没有任何向上滚动的可能性(我仍然可以向下滚动)。

如何解决?

编辑 1: 这是一些代码:

可以在简单的html网页上打印的html代码:

<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<style>
/**
 *     Change the basic background color of the page
 */
html
{
    background-color: blue;
}

/**
 *     Set the body as a 1024 x 768 rectangle in center of the screen
 */
body
{
    background-color:                   red;
    font-family:      TradeGothic, sans-serif;
    margin-left:                       -512px;
    margin-top:                        -384px;
    position:                        absolute;
    height:                             768px;
    width:                             1024px;
    left:                                 50%;
    top:                                  50%;
}
</style>
</head>
<body>
some text
</body>
</html>

【问题讨论】:

    标签: html css


    【解决方案1】:

    添加这个:

    html {
        position: relative;
        min-width: 1024px;
        min-height: 768px;
        height: 100%;
    }
    

    http://jsfiddle.net/thirtydot/TGjN8/9/(全屏:http://jsfiddle.net/thirtydot/TGjN8/9/show/

    【讨论】:

    • 哇,非常感谢!!!我可以问你为什么它有效吗?虽然我完全理解 100% 的高度(但我认为这是默认值),但我并没有完全理解最小宽度的意义。我没想到有 50k 声望的人会回答这个问题……非常感谢!
    • 还添加:位置:相对;是否可以使视口相对于窗口? (在 0;0)
    • 不客气。 position: relative 将绝对定位的body 锚定到htmlmin-* 防止html 变得小于body,从而确保滚动。所以,“是的”。
    • 非常感谢,这个答案真的很有帮助也很有趣。我从中学到了很多!
    猜你喜欢
    • 1970-01-01
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多