position + margin (元素有宽高)

这种方式需要为元素设置宽高,父元素绝对定位,子元素相对定位,margin减去自身宽高的一半

  1. <style>
  2. .c {
  3. width: 200px;
  4. height: 200px;
  5. background-color: #ccc;
  6. position: absolute;
  7. top: 50%;
  8. left: 50%;
  9. margin-left: -100px;
  10. margin-top: -100px;
  11. }
  12. </style>
  13. <div class="c"></div>

position + margin (元素无宽高)

这种方式不需要元素设置宽高,父元素绝对定位,子元素相对定位

  1. <style>
  2. .c {
  3. width: 200px;
  4. height: 200px;
  5. background-color: #ccc;
  6. position: absolute;
  7. top: 0;
  8. left: 0;
  9. right: 0;
  10. bottom: 0;
  11. margin: auto;
  12. }
  13. </style>
  14. <div class="c"></div>

position + transform(元素无宽高)

这种方式不需要元素设置宽高,父元素绝对定位,子元素相对定位

  1. <style>
  2. .c {
  3. width: 200px;
  4. height: 200px;
  5. background-color: #ccc;
  6. position: absolute;
  7. top: 50%;
  8. left: 50%;
  9. transform: translate(-50%, -50%);
  10. }
  11. </style>
  12. <div class="c"></div>

flex布局(元素无宽高)

  1. <style>
  2. .f {
  3. width: 100%;
  4. height: 100%;
  5. display: flex;
  6. justify-content: center;
  7. align-items: center;
  8. }
  9. </style>
  10. <div class="f"><div class="c">水平垂直居中</div></div>