不定宽高垂直水平居中的几种方法

  • 父子定位,子元素使用 transfrom:translate();属性

.box {
    width: 700px;

    height: 700px;

    border: 1px solid red;

    margin: 50pxauto;

    position: relative;

}
.box1 {
     width: 100px;
     height: 100px;
     background-color: green;
     position: absolute;
     left: 50%;
     top:50%;
     transform: translate(-50%, -50%); 
}

父子定位,子元素使用 left right top bottom margin: auto;属性

.box {
    width: 700px;
    height: 700px;
    border: 1px solid red;
    margin: 50pxauto;
    position: relative;

}
.box1 {
     width: 100px;
     height: 100px;
     background-color: green;
     position: absolute;
     top: 50%;
     left: 50%;
     margin-left: -50px;
     margin-top: -50px;
}
  • 使用 flex 布局
.box {
      width: 700px;
      height: 700px;
      border: 1px solid red;
      margin: 50px auto;
      display: flex;
      justify-content: center;  
      align-items: center; 
    }
.box1 {
      width: 100px;
      height: 100px;
      background-color: green;
}

猜你喜欢

转载自blog.csdn.net/weixin_43478869/article/details/84648623