<无用的知识又增加了>七种居中方式

207 阅读1分钟

项目最常用的两种方式

.container {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%); // 自身宽度和高度的一半
    border: 1px solid red;
}

.container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

无用的五种方式

// 1
.container {
    width: 300px;
    height: 300px;
    line-height: 300px; // important
    text-align: center;
    border: 1px solid red;
}
// 2  mt 高度的一半 ml宽度一半
.container {
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -150px;
    margin-top: -150px;
    width: 300px;
    height: 300px;
    border: 1px solid red;
}
// 3 计算属性50%减去一半
.container {
    position: absolute;
    left: calc(50% - 150px);
    top: calc(50% - 150px);
    width: 300px;
    height: 300px;
    border: 1px solid red;
}
// 4 
.container {
    width: 300px;
    margin: 50vh auto 0;
    transform: translateY(-50%);
    border: 1px solid red;
}
// 
.container {
    display: flex;
    height: 100vh;
}

.inner {
    margin: auto;
}
// 5 display: table来模拟表格,并给子元素设置display: table-cell,
让其成为表格的某个单元格,同时设置vertical-align:  middle,即可实现垂直居中布局
.container {
    display: table;         /* 让div以表格的形式渲染 */
    width: 100%;
    border: 1px solid red;
}

.inner {
    display: table-cell;    /* 让子元素以表格的单元格形式渲染 */
    text-align: center;
    vertical-align: middle;
}