题目:子盒子在父盒子里居中对齐
一:父盒子加相对定位,子盒子加绝对定位实现。
代码:
1.定义父盒子与子盒子:
<div class="jz">
<div class="jz2">
</div>
</div>
2.css样式实现子盒子居中对齐:
.jz{
position: relative;
height: 500px;
width: 500px;
background-color: rgb(24, 24, 24);
}
.jz2{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
height: 100px;
width: 100px;
background-color: rgb(8, 12, 241);
}
关键:
position: xxxxx; 定位属性
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
效果:
二:父盒子添加flex布局
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.jz{
height: 500px;
width: 500px;
background-color: rgb(24, 24, 24);
display: flex;
justify-content: center;
align-items: center;
}
.jz2{
height: 100px;
width: 100px;
background-color: rgb(8, 12, 241);
}
</style>
</head>
<body>
<div class="jz">
<div class="jz2">
</div>
</div>
</body>
</html>
效果是一样的