水平垂直居中的方式

5次阅读

共计 721 个字符,预计需要花费 2 分钟才能阅读完成。

  • 方式一 absolute && translate
.parent {position: relative;}
.son {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
  • 方式二 absolute
.parent {position: relative;}
.son {
    position: absolute;
    margin: auto;
    width: 100px;
    height: 50px;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}
  • 方式三 table && table-cell
.parent {
    display: table;
    width: 100%;
    height: 50px;
}
.son {
    display: table-cell;
    vertical-align: middle;
}
  • 方式四
.parent {display: flex;} 
.son {margin: auto;}

.parent {
    display: flex;
    justify-content: center;
    align-items: center;
}

.parent {
    display: flex;
    justify-content: center;
}
.son {align-self: center;}
  • 方式五
.parent {display: grid;}
.son {
    justify-self: center; 
    align-self: center;
}
  • 方式六
.parent {position: relative;}
/* 无需知道被居中元素的宽高 */
.son  {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}

正文完
 0