在父盒子里面水平垂直居中的3种方法

104 阅读1分钟

方法一:

.box1 {
      position: absolute;
      /* 父元素宽高的一半 */
      top: 50%;
      left: 50%;
      width: 100px;
      height: 100px;
      /* 本身宽高的一半 */
      transform: translate(-50%, -50%);
    }

方法二:

.box2 {
            position: absolute;
            /* 父元素宽高的一半 */
            top: 50%;
            left: 50%;
            width: 100px;
            height: 100px;
            background-color: green;
            /* 自身宽高的一半(在知道自己的宽高时) */
            margin-top: -50px;
            margin-left: -50px;
            /*这里不能用
            margin-top: -50%;
            margin-left: -50%;
            这里的50%是相对于父元素的
            */

方法三

.box3 {
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            margin: auto;
            width: 100px;
            height: 100px;
            background-color: red;
        }