方法1:宽度和高度已知的

给父元素相对定位
给子元素绝对定位
left: 50%;top: 50%;
margin-left: 负的宽度一半。
margin-top: 负的高度一半;

方法2:宽度和高度自己未知

意思就是说子盒子本身还是有宽度和高度的,只是自己未知。
思路:
给父盒子相对定位
给子盒子绝对定位
top、right、bottom、left全为0
margin: auto;

方法3:flex布局

父元素:display:flex;
子元素可居中

  1. .center{
  2. display: flex;
  3. justify-content: center;//实现水平居中
  4. align-items: center;//实现垂直居中
  5. }

方法四:平移 定位+transform

  1. 父元素
  2. .parent_box{
  3. width: 400px;
  4. height: 200px;
  5. background: red;
  6. position: relative;
  7. }
  8. 子元素
  9. .child_box{
  10. width: 200px;
  11. height: 100px;
  12. background: #9ff;
  13. position: absolute;
  14. top: 50%;
  15. left: 50%;
  16. transform: translate( -50%,-50%);
  17. }

方法五:table-cell布局

父级 display: table-cell; vertical-align: middle; 子级 margin: 0 auto;