Article Directory
Initial state
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>垂直居中</title>
</head>
<body>
<div id="app" style="border: 1px solid red;width: 100px;height: 100px;margin: auto;"></div>
</body>
</html>
Horizontally centered
Add tomargin:auto
<div id="app" style="margin: auto;border: 1px solid red;width: 100px;height: 100px;"></div>
Or
absolute layout + left 50% + transform 50% of the left translation width
Vertically centered
Absolute layout + top 50% + transform up to 50% of the height
<style>
#app{
position: absolute;
top: 50%;
transform: translate(0,-50%);
}
</style>
<div id="app" style="border: 1px solid red;width: 100px;height: 100px;"></div>
Vertically centered + Horizontally centered
method one
Absolute layout + margin: auto + top/right/bottom/left values are equal
<style>
#app{
position: absolute;
margin: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
</style>
<div id="app" style="border: 1px solid red;width: 100px;height: 100px;"></div>
Method Two
Absolute layout + left 50% + top 50% + transform 50% to the left and up, the effect picture is the same as above
<style>
#app{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
</style>
<div id="app" style="border: 1px solid red;width: 100px;height: 100px;"></div>