css居中相关面试题

admin2024-01-20 21:32:20

css水平居中

/*方法1:inline-block + text-align */
.parent {
    text-algin: center;
}
.child {
    display: inline-block;
}

/*方法2:block + margin */

.child {
    width: 80px /*这个必须要设置宽度*/
    display: block;/*设置成table可以不设置宽度*/
    margin: 0 auto;
}

/*方法3: absolute + transform/margin*/
.parent {
    position: relative;
}
.child {
    position: absolute;
    left: 50%;
    transform: translateX(-50%)
}

垂直居中

/*方法1*/
.parent {
    display: tabel-cell;/* 单元格的内容是可以设置水平垂直对齐的 */
    verticle-algin: middle;/* 用于设置文本内容的垂直方向对齐方式 */
}

/*方法2*/
.parent {
    position: relative;
}
.child {
    position: absolute;
    top: 50%
    transform: translateY(-50%)
}

一般就是这几种方法,组合起来一共6种