<div id="wrap">
<div id="box">
</div>
</div>
效果图
方法一
#wrap{ width: 300px; height: 300px; background: lightblue; position: relative; } #box{ width: 150px; height: 150px; background: pink; position: absolute; top:50%; left:50%; transform: translate(-50%,-50%); }
方法二
#wrap{ width: 300px; height: 300px; background: lightblue; position: relative; } #box{ width: 150px; height: 150px; background: pink; position: absolute; top:0; left:0; right:0; bottom:0; margin:auto; }
方法三
#wrap{ width: 300px; height: 300px; background: lightblue; position: relative; } #box{ width: 150px; height: 150px; background: pink; position: absolute; top:50%; left:50%; margin-left: -75px; margin-top: -75px; }
方法四
#wrap{ width: 300px; height: 300px; background: lightblue; display: flex; justify-content:center; align-items:center; } #box{ width: 150px; height: 150px; background: pink; }