1.元素水平居中:元素是行内块元素,可以设置宽度的情况下,margin: 0 auto;
2.一个已知宽度和高度的开启了position: absolute;的元素(父元素开启position: relative;)
<div class="wrap">
<div class="content"></div>
</div>
<style>
.wrap { background-color: red; 300px; height: 300px; position: relative; }
.content { background-color: yellow; 100px; height: 100px; position: absolute; left: 50%; top: 50%; margin: -50px 0 0 -50px; }
</style>
3.一个宽高不固定的元素,同上方式,把固定可知的margin替换成 transform: translate(-50%, -50%);
<div class="wrap">
<div class="content">11111</div>
</div>
<style>
.wrap { background-color: red; 300px; height: 300px; position: relative; }
.content { background-color: yellow; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); }
</style>
4.flex弹性布局
<div class="wrap">
<div class="content"> 11111 </div>
</div>
<style>
.wrap { display: flex; justify-content: center; align-items: center; 300px; height: 300px;background: red;}
.content { background-color: yellow; }
</style>
5. table布局