子绝父相第1种
<head>
<style>
.father {
position: relative;
width: 500px;
height: 500px;
background-color: pink;
}
.son {
position: absolute;
left: 0;
right: 0;
bottom: 0;
top: 0;
/* 居中 */
margin: auto;
width: 200px;
height: 200px;
background-color: skyblue;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
子绝父相第2种
<head>
<style>
.father {
position: relative;
width: 500px;
height: 500px;
background-color: pink;
}
.son {
position: absolute;
left: 50%;
top: 50%;
/* 移动子盒子宽度的一半 */
margin-left: -100px;
margin-top: -100px;
width: 200px;
height: 200px;
background-color: skyblue;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
子绝父相第3种
<head>
<style>
.father {
position: relative;
width: 500px;
height: 500px;
background-color: pink;
}
.son {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
background-color: skyblue;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
网格布局(grid)
<head>
<style>
.father {
display: grid;
place-items: center;
width: 500px;
height: 500px;
background-color: pink;
}
.son {
width: 200px;
height: 200px;
background-color: skyblue;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
flex布局
<head>
<style>
.father {
display: flex;
/* 选择主轴方向 */
justify-content: center;
/* 侧轴方向 */
align-items: center;
width: 500px;
height: 500px;
background-color: pink;
}
.son {
width: 200px;
height: 200px;
background-color: skyblue;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>