css实现水平垂直居中

栗子1

无固定宽高

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
29

<html>
<head>
<meta charset="utf-8">
<title>居中栗子1</title>
<style>
html,body{
width:60%;
height:100%;
position:relative;
margin:0 auto;
}

.wrap{
background-color: #ddd;
position:absolute;
width:100%;
top:50%;
left:50%;
transform: translate(-50%,-50%);
}
</style>

</head>
<body>
<div class="wrap">
温馨提示
</div>
</body>
</html>

栗子2

有固定宽高

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

<html>
<head>
<meta charset="utf-8">
<title>居中栗子2</title>
<style>
.wrap{
background:#ddd;
position: absolute;
left: 50%;
top: 50%;
margin: -60px 0 0 -60px;
width: 120px;
height: 120px;
}
</style>

</head>
<body>
<div class="wrap">
温馨提示
</div>
</body>
</html>