1. 父相子绝-left&margin-left-top&margin-top
<style>
.father{
position: relative;
width: 500px;
height: 300px;
background-color: black;
}
.son{
position: absolute;
top:50%;
left: 50%;
margin-top: -20px;
margin-left: -20px;
height: 40px;
width: 40px;
background-color: #66CCFF;
}
</style>
<div class="father">
<div class="son">
<!--我是块级元素-->
</div>
</div>
2. 父相子绝-top&bottom&left&right&margin
<style>
.father{
position: relative;
width: 500px;
height: 300px;
background-color: black;
}
.son{
position: absolute;
left:0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
height: 200px;
width: 200px;
background-color: #66CCFF;
}
</style>
<div class="father">
<div class="son">
我是块级元素
</div>
</div>
3. 父相子绝-left&top&transform
<style>
.father{
position: relative;
width: 500px;
height: 300px;
background-color: black;
}
.son{
position: absolute;
top:50%;
left: 50%;
transform: translate(-50%,-50%);
height: 40px;
width: 40px;
background-color: #66CCFF;
}
</style>
<div class="father">
<div class="son">
<!--我是块级元素-->
</div>
</div>
4. flex
<style>
.father{
display: flex;
justify-content:center;
align-items: center;
width: 500px;
height: 300px;
background-color: black;
}
.son{
height: 40px;
width: 40px;
background-color: #66CCFF;
}
</style>
<div class="father">
<div class="son">
<!--我是块级元素-->
</div>
</div>
5. table-cell
<style>
.father{
display: table-cell;
vertical-align: middle;
width: 500px;
height: 300px;
background-color: black;
}
.son{
margin: auto;
width:300px;
height: 100px;
background-color: #66CCFF;
}
</style>
<div class="father">
<div class="son">
<!--我是块级元素-->
</div>
</div>