元素垂直水平居中的几种方法

HTML:

1
2
3
<body>
<div></div>
</body>

方法1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
body {
width: 100%;
height: 100vh;
border: 1px solid blue;
}
body div {
height: 100px;
width: 100px;
background-color: red;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}

方法2:

1
2
3
4
5
6
7
8
9
10
11
12
body {
width: 100%;
height: 100vh;
border: 1px solid blue;
display: flex;
}
body div {
height: 100px;
width: 100px;
background-color: red;
margin: auto;
}

方法3:

1
2
3
4
5
6
7
8
9
10
11
12
13
body {
width: 100%;
height: 100vh;
border: 1px solid blue;
display: flex;
justify-content: center;
align-items: center;
}
body div {
height: 100px;
width: 100px;
background-color: red;
}

方法4:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
body {
width: 100%;
height: 100vh;
border: 1px solid blue;
}
body div {
height: 100px;
width: 100px;
background-color: red;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}