HTML:
<div class="fa">
<div class="son"></div>
</div>
css1:
.fa {
position: relative;
width: 600px;
height: 400px;
margin: 0 auto;
margin-top: 100px;
background-color: coral;
}
.son {
position: absolute;
width: 200px;
height: 200px;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -100px;
background-color: darkgray;
}
这种方式,需要已知子元素的宽高.
css2:
.fa {
position: relative;
width: 600px;
height: 400px;
margin: 0 auto;
margin-top: 100px;
background-color: coral;
}
.son {
position: absolute;
width: 200px;
height: 200px;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
background-color: darkgray;
}
这种方式,子元素与父元素之间,被margin填充