html 布局结构如下
<div class="outerBox"> <div class="innerBox"></div> </div>
第一种 使用flex
.outerBox { height: 400px; background-color: rgb(12, 243, 232); display: flex; justify-content: center; align-items: center; } .innerBox { width: 200px; height: 200px; background-color: pink; }
第二种 position + margin:auto
.outerBox { height: 400px; background-color: rgb(12, 243, 232); position: relative; } .innerBox { width: 200px; height: 200px; background-color: pink; position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; }
第三种 position + margin负边距
.outerBox { height: 400px; background-color: rgb(12, 243, 232); position: relative; } .innerBox { width: 200px; height: 200px; background-color: pink; position: absolute; left: 50%; top: 50%; margin-left: -100px; margin-top: -100px; }
第四种 transform: translate
.outerBox { height: 400px; background-color: rgb(12, 243, 232); position: relative; } .innerBox { width: 200px; height: 200px; background-color: pink; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }