HTML代码
/* 以下内容只写css样式 */
<div id="wrap">
<div id="box">111</div>
</div>
1. 使用定位加位移,优点:元素不需要设置固定宽度
#wrap{
width: 200px;
height: 200px;
background-color: #bfa;
position: absolute;
}
#box{
background-color: pink;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
2. 使用flex伸缩盒模型,缺点:IE10以下不兼容
#wrap{
width: 200px;
height: 200px;
background-color: #bfa;
display: flex;
justify-content: center;
align-items: center;
}
#box{
background-color: pink;
}
3. 使用margin和定位,让浏览器计算位置,缺点:元素需要设置固定宽高
#wrap{
width: 200px;
height: 200px;
background-color: #bfa;
position: absolute;
}
#box{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
margin: auto;
left: 0;
top: 0;
right: 0;
bottom: 0;
}
4. 使用定位加外边距,缺点:元素需要设置固定宽度
#wrap{
width: 200px;
height: 200px;
background-color: #bfa;
position: absolute;
}
#box{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
}