css让父盒子里面的子盒子实现水平垂直居中的三种方法

107 阅读1分钟

1、通过定位(子绝父相)和外边距实现子盒子水平垂直居中

<style>
    .father {
      position: relative;
      width: 600px;
      height: 400px;
      border: 1px solid #000;
    }

    .son {
      position: absolute;
      left: 50%;
      top: 50%;
      margin-left: -100px;
      margin-top: -50px;
      width: 200px;
      height: 100px;
      background-color: pink;
    }
    </style>
        <div class="father">
           <div class="son"></div>
        </div>

2、通过定位(子绝父相)和位移实现子盒子水平垂直居中

<style>
   .father {
      position: relative;
      width: 600px;
      height: 400px;
      border: 1px solid #000;
    }

    .son {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      width: 200px;
      height: 100px;
      background-color: pink;
    }
    </style>
        <div class="father">
           <div class="son"></div>
       </div>

3、通过flex弹性布局实现子盒子水平垂直居中

<style>
        * {
            margin: 0;
            padding: 0
        }

        .father {
            width: 400px;
            height: 400px;
            border: 1px solid #000;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .son {

            width: 100px;
            height: 100px;
            background: red;
        }
    </style>
        <div class="father">
           <div class="son"></div>
        </div>