CSS居中总结

水平居中

CSS3 absolute+transform

通用——宽高未知~~

.parent { 
    position: relative;     
}
.child { 
    position: absolute; 
    left: 50%;
    transform: translateX(-50%); 
}

flex

通用——宽高未知~~

.parent { 
    display: flex; 
    justify-content: center;    /* 主轴对齐方式,默认主轴为水平 */
}

margin auto

有宽度的块元素

float+relative

.child { 
    width: 100px; 
    float: left; 
    position: relative; 
    left: 50%; 
    margin-left: -50px; 
}

absolute

.parent { 
    position: relative;
} 
.child { 
    position: absolute; 
    width: 100px; 
    left: 50%; 
    margin-left: -50px; 
}
.child { 
    position: absolute; 
    width: 100px; 
    left:0;
    top:0;
    margin:0 auto;
}

垂直居中

transform+absolute

通用——宽高未知~~

.parent { 
    position: relative;     
}
.child { 
    position: absolute; 
    top: 50%;
    transform: translateY(-50%); 
}

flex

通用——宽高未知~~

.parent { 
    display: flex; 
    align-items: center;    /* 交叉轴对齐方式 */
}

已知宽高:absolute

.parent { 
    position: relative; 
}
.child{ 
    position: absolute; 
    top: 50%; 
    height: 100px; 
    margin-top: -50px; 
}
.parent { 
    position: relative;
} 
.child{ 
    position: absolute; 
    top: 0; 
    bottom: 0; 
    height: 100px; 
    margin: auto 0; 
}

绝对居中

可以封装做弹出窗口。

div { 
    width: 100px; 
    height: 100px; 
    margin: auto; 
    position: fixed; /* absolute也可以 */
    top: 0; 
    right: 0; 
    bottom: 0; 
    left: 0; 
}
posted @ 2020-04-07 13:41  秋秋秋白  阅读(119)  评论(0编辑  收藏  举报