1.利用translate的偏移定位。
#app{ background:green; width:500px; height:500px; position:relative; } #box{ background:red; position:absolute; left:50%; top:50%; transform:translate(-50%,-50%); }
2.利用flex布局
#app { display: flex; justify-content: center; align-items: center; width: 500px; height: 500px; } #box{ width: 100px; height: 100px; }
备注:css遮罩层
<div id='app'></div> <div id="box"></div>
#app{ background:green; position:fixed; top:0;left:0;right:0;bottom:0; } #box{ background:red; position:absolute; left:0; top:0; right:0; bottom:0; width:300px; height:300px; margin:auto; }