使用 Flexbox 布局实现 div 垂直居中
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.father {
width: 200px;
height: 200px;
border: 1px solid red;
display: flex;
align-items: center;
/* 垂直居中 */
justify-content: center;
/* 水平居中 */
}
.child {
width: 100px;
height: 100px;
border: 1px solid blue;
}
</style>
<body>
<div>
<div class="father">
<div class="child"></div>
</div>
</div>
</body>
</html>
使用 position 属性和 transform 属性实现垂直居中:
.father {
width: 200px;
height: 200px;
border: 1px solid red;
position: relative;
}
.child {
width: 100px;
height: 100px;
border: 1px solid blue;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
使用 position 和 margin:auto 实现
.father {
position: relative;
width: 200px;
height: 200px;
border: 1px solid red;
}
.child {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
width: 100px;
height: 100px;
border: 1px solid blue;
}