1.元素水平居中:元素是行内块元素,可以设置宽度的情况下,margin: 0 auto;
2.一个已知宽度和高度的开启了position: absolute;的元素(父元素开启position: relative;)
<div class="wrap"> <div class="content"></div></div>
<style> .wrap { background-color: red; width: 300px; height: 300px; position: relative; } .content { background-color: yellow; width: 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; width: 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; width: 300px; height: 300px;background: red;} .content { background-color: yellow; }</style>
5. table布局
来源:https://www.cnblogs.com/fairy62/p/9811894.html