1. 通过定位,给父盒子相对定位,给子盒子绝对定位,top.left为50%,再margin-top:-(子盒子高的一半)px,margin-left:-(子盒子宽的一半)px

      注:需要知道盒子的宽高

      1. <style>
      2. div {
      3. position: relative;
      4. height: 400px;
      5. width: 400px;
      6. background-color: pink;
      7. }
      8. span {
      9. position: absolute;
      10. top: 50%;
      11. left: 50%;
      12. margin-left: -50px;
      13. margin-top: -50px;
      14. display: block;
      15. width: 100px;
      16. height: 100px;
      17. background-color: purple;
      18. }
      19. </style>
    2. 不依赖计算盒子宽高进行定位,可以用transform:translate 移动自身的一半就行

      1. <style>
      2. div {
      3. position: relative;
      4. height: 400px;
      5. width: 400px;
      6. background-color: pink;
      7. }
      8. span {
      9. position: absolute;
      10. top: 50%;
      11. left: 50%;
      12. transform: translate(-50%, -50%);
      13. display: block;
      14. width: 100px;
      15. height: 100px;
      16. background-color: purple;
      17. }
      18. </style>
    3. 子盒子定位时,top.left.bottom.right都设置为0,然后设置margin:auto , 也能实现居中

      1. <style>
      2. div {
      3. position: relative;
      4. height: 400px;
      5. width: 400px;
      6. background-color: pink;
      7. }
      8. span {
      9. position: absolute;
      10. top: 0;
      11. left: 0;
      12. bottom: 0;
      13. right: 0;
      14. margin: auto;
      15. display: block;
      16. width: 100px;
      17. height: 100px;
      18. background-color: purple;
      19. }
      20. </style>
    1. 通过flex布局,设置垂直和水平都居中( 设置为水平居中justify-content: center; 设置为垂直居中align-items: center;)

      1. <style>
      2. div {
      3. display: flex;
      4. justify-content: center;
      5. align-items: center;
      6. height: 400px;
      7. width: 400px;
      8. background-color: pink;
      9. }
      10. span {
      11. display: block;
      12. width: 100px;
      13. height: 100px;
      14. background-color: purple;
      15. }
      16. </style>
    2. 通过flex布局,给子盒子设置margin:auto

      1. <style>
      2. div {
      3. display: flex;
      4. height: 400px;
      5. width: 400px;
      6. background-color: pink;
      7. }
      8. span {
      9. margin: auto;
      10. width: 100px;
      11. height: 100px;
      12. background-color: purple;
      13. }
      14. </style>
    3. 通过display:table-cell 给子盒子设置display:inline-block,父盒子设置vertical-align:middle; text-align:center;

      1. <style>
      2. div {
      3. display:table-cell;
      4. vertical-align:middle;
      5. text-align:center;
      6. height: 400px;
      7. width: 400px;
      8. background-color: pink;
      9. }
      10. span {
      11. display:inline-block;
      12. width: 100px;
      13. height: 100px;
      14. background-color: purple;
      15. }
      16. </style>