如何实现一个元素居中

168 阅读1分钟

1.传统margin:0 auto;

2.未知自身元素的宽高 利用c3属性

.element {
    position: absolute; 
    left: 50%; 
    top: 50%;
    transform: translate(-50%, -50%);    /* 50%为自身尺寸的一半 */
}

3.使用兼容性更好的方法

.element {
    position: absolute; 
    left: 0; 
    top: 0; 
    right: 0; 
    bottom: 0;
    margin: auto;    /*实现完全居中,可以设置横向居中或者纵向居中*/
}

若只要横向居中,只需left:0 和 right:0 就可以了, top 和 bottom 不要设置

4.父元素设置flex

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