如何使固定大小的主体(或div)始终位于页面的中心(甚至垂直!)

时间:2012-02-03 02:20:15

标签: html css

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

我使用距离顶部50%的技巧,然后我(绝对)将身体定位在-384px,这是768的一半。

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

如何解决?

编辑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>

1 个答案:

答案 0 :(得分:9)

添加:

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

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