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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9122904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 22:15:36  来源:igfitidea点击:

How to make the body (or div) of fixed size stay always in the center of the page (even vertically!)

htmlcss

提问by Francesco Belladonna

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 trickof 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>

回答by thirtydot

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/show/