1. 方法一

    父元素设置为flex布局,并设置justify-content:center和align-items:center,令其主轴和交叉轴的对齐方式为居中

    1. <div class="fu">
    2. <div class="son">
    3. 子元素
    4. </div>
    5. </div>
    6. .fu {
    7. height: 500px;
    8. width: 500px;
    9. background-color: burlywood;
    10. display: flex;
    11. justify-content: center;
    12. align-items: center;
    13. }
    14. .son {
    15. height: 100px;
    16. width: 100px;
    17. background-color: red;
    18. }
    1. 方法二

    父元素设置为flex布局,子元素的margin设置为auto

    1. <div class="fu">
    2. <div class="son">
    3. 子元素
    4. </div>
    5. </div>
    6. .fu {
    7. height: 500px;
    8. width: 500px;
    9. background-color: burlywood;
    10. display: flex;
    11. }
    12. .son {
    13. height: 100px;
    14. width: 100px;
    15. background-color: red;
    16. margin:auto;
    17. }
    1. 方法三

    父元素设置为绝对定位,position:relative,子元素设置为绝对定位,position: absolute;设置距离top:50%,左边left:50%,设置transform:translate(-50%,-50%)

    1. <div class="fu">
    2. <div class="son">
    3. 子元素
    4. </div>
    5. </div>
    6. .fu {
    7. height: 500px;
    8. width: 500px;
    9. background-color: burlywood;
    10. position: relative;
    11. }
    12. .son {
    13. height: 100px;
    14. width: 100px;
    15. background-color: red;
    16. position: absolute;
    17. top:50%;
    18. left: 50%;
    19. transform: translate(-50%,-50%);
    20. }