让一个不定宽高的盒子水平垂直居中
一、使用定位的方式
.father{
position: relative;
width: 500px;
height: 300px;
background-color: skyblue;
}
.son{
width: 40px;
height: 40px;
background-color: orange;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
<div class="father">
<div class="son"></div>
</div>
二、使用flex布局的方式
.father{
display: flex;
justify-content: center;
align-items: center;
width: 500px;
height: 300px;
background-color: skyblue;
}
.son{
width: 40px;
height: 40px;
background-color: orange;
}
<div class="father">
<div class="son"></div>
</div>
三、使用Css3属性
.father{
position: relative;
width: 500px;
height: 300px;
background-color: skyblue;
}
.son{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
width: 40px;
height: 40px;
background-color: orange;
}
<div class="father">
<div class="son"></div>
</div>