实现效果:

【CSS】一个DIV在另一个DIV上下左右居中(示例)_前端

代码:

<!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>
</head>

<style>
.box1 {
width: 300px;
height: 300px;
background-color: rgb(209, 233, 209);
}
.box2 {
width: 150px;
height: 150px;
background-color: rgb(245, 196, 169);
position: relative;
margin: 0 auto;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);

/* 文字居中 */
text-align: center;
line-height: 145px;
}
</style>

<body>
<div class="box1">
<div class="box2">居中了</div>
</div>
</body>
</html>