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

时间:2022-03-11 21:28:19

I'm trying to make a 1024x768 body to stay always in the center of the page (top-bottom with same spacing, left-right too) however I'm having troubles in doing it.

我试着让一个1024x768的身体一直保持在页面的中心位置(同样的间隔,也有同样的间距),但是我在做这件事时遇到了麻烦。

I used the trick of spacing from top by 50%, then I positioned (absolutely) the body at -384px, which is half of 768.

我使用了从顶部间隔50%的技巧,然后(绝对地)将主体定位为-384px,也就是768的一半。

However this method gives me a problem: if your window is smaller than 768px, you get a scrollbar but a part of the upperside of the body get cut, without any possibility to scroll up (I can still scroll down).

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

How to solve it?

如何解决这个问题?

Edit 1: Here is some code:

编辑1:这里有一些代码:

Html code that can be printed on a simple html web page:

可以在简单的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 个解决方案

#1


9  

Add this:

添加:

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

http://jsfiddle.net/thirtydot/TGjN8/9/ (fullscreen: http://jsfiddle.net/thirtydot/TGjN8/9/show/ )

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

#1


9  

Add this:

添加:

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

http://jsfiddle.net/thirtydot/TGjN8/9/ (fullscreen: http://jsfiddle.net/thirtydot/TGjN8/9/show/ )

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