一、已经元素宽高(1)定位布局
<div class="box">
<div class="contain"></div>
</div>
.box{
width:200px;
height: 200px;
background: red;
margin: 0 auto;
position: relative;
}
.contain{
width: 50px;
height: 50px;
background: gray;
position: absolute;
left: 50%;
top: 50%;
margin: -25px 0 0 -25px;
}
二、已经元素宽高(2)定位布局
.box{
width:200px;
height: 200px;
background: red;
margin: 0 auto;
position: relative;
}
.contain{
width: 50px;
height: 50px;
background: gray;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%)
}
三、已经元素宽高(3) flex布局
.box{
width:200px;
height: 200px;
background: red;
margin: 0 auto;
display: flex;
justify-content: center;
align-items: center;
}
.contain{
width: 50px;
height: 50px;
background: gray;
}
四、未知元素宽度(这种是宽度自适应)
.box{
width:200px;
height: 200px;
background: red;
margin: 0 auto;
position: relative;
}
.contain{
height: 50px;
background: gray;
position: absolute;
margin: auto;
left: 0;
top: 0;
right: 0;
bottom: 0;
}