div自适应浏览器窗口居中显示

html代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .center {
            position: absolute;
            left: 50%;
            top: 50%;
            margin-left: -600px;
            margin-top: -200px;
            width: 1200px;
            height: 400px;
            background: #4fcc8d;
        }

    </style>
</head>

<body>
    <div>
        <div class="center"></div>
    </div>
</body>

</html>

其原理:先使用”left: 50%; top: 50%;”让”div”的左上角位于页面正中央,再使用margin向左向上移动一般的”div”的高度和宽度。