1,使用定位
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
<style>
.box {
position: absolute;
//top:50%, left:50%,是以左上角为原点
top: 50%;
left: 50%;
//translate(-50%, -50%)作用是,往上(X轴),左(Y轴)移动自身长度的50%,以使其居于中心位置
transform: translate(-50%,-50%);
}
</style>
</head>
<body>
<div class="box" style="width:300px; height: 300px; background-color: teal;"></div>
</body>
</html>
2,使用弹性布局
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
<style>
.box {
display: flex;
/* justify-content:center;定义项目在主轴(水平方向)上居中对齐 */
justify-content: center;
/* align-items:center;定义项目在交叉轴(垂直方向)上居中对齐 */
align-items: center;
}
.box2 {
width: 200px;
height: 200px;
background-color: red;
}
</style>
</head>
<body>
<div class="box" style="width:300px; height: 300px; background-color: teal;">
<div class="box2"></div>
</div>
</body>
</html>