1、未知元素宽高
1.1、flex居中
/* flex居中 */
.box{
width: 100px;
height: 100px;
display: flex;
justify-content: center;
background-color: powderblue;
align-items: center;
}
.small_box{
width: 50px;
height: 50px;
background-color: pink;
}
1.2、绝对定位居中
/* 未知宽高,绝对定位居中 */
.box{
width: 100px;
height: 100px;
position: relative;
background-color: powderblue;
}
.small_box{
width: 50px;
height: 50px;
position: absolute;
top: 0;
left:0;
bottom: 0;
right: 0;
margin: auto;
background-color: pink;
}
1.3未知宽高,绝对定位加移动
/* 未知宽高、定位加移动居中 */
.box{
width: 100px;
height: 100px;
position: relative;
background-color: powderblue;
}
.small_box{
width: 50px;
height: 50px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
background-color: pink;
}
2、已知宽高
2.1 绝对定位
/* 已知元素宽高 */
.box{
width: 100px;
height: 100px;
position: relative;
background-color: powderblue;
}
.small_box{
width: 50px;
height: 50px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -25px;
margin-left: -25px;
background-color: pink;
}