跳至主要內容

css 水平垂直居中

fxss原创css大约 1 分钟

下面为公共代码:

<div class="box">
    <div class="small">small</div>
</div>
.box {
    width: 300px;
    height: 300px;
    background: #ddd;
}
.small {
    background: red;
}

absolute + margin实现

absolute + margin 第1种

.box {
    position: relative;
}
.small {
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -50px 0 0 -50px;
    width: 100px;
    height: 100px;
}

Open in CodePenopen in new window

absolute + margin 第2种

.box {
    position: relative;
}
.small {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
    width: 100px;
    height: 100px;
}

Open in CodePenopen in new window

absolute + calc 实现

.box {
    position: relative;
}
.small {
    position: absolute;
    top: calc(50% - 50px);
    left: calc(50% - 50px);
    width: 100px;
    height: 100px;
}

Open in CodePenopen in new window

absolute + transform 实现

.box {
    position: relative;
}
.small {
    position: absolute;
    top: 50%;
    left: 50%;
    /* transform: translate(-50%,-50%); */
    transform: translate3d(-50%,-50%,0);
    width: 100px;
    height: 100px;
}

Open in CodePenopen in new window

转行内元素

.box {
    line-height: 300px;
    text-align: center;
    font-size: 0px;
}
.small {
    padding: 6px 10px;
    font-size: 16px;
    display: inline-block;
    vertical-align: middle;
    line-height: 16px;
}

Open in CodePenopen in new window

table-cell

.box {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.small {
    padding: 6px 10px;
    display: inline-block;
}

Open in CodePenopen in new window

flex

flex 第1种

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

Open in CodePenopen in new window

flex 第2种

.box {
    display: flex;
    justify-content: center;
}
.small {
    align-self: center;
}

Open in CodePenopen in new window

grid

grid 第1种

.box {
    display: grid;
    justify-items: center;
    align-items: center;
}

Open in CodePenopen in new window

grid 第2种

.box {
    display: grid;
}
.small {
    justify-self: center;
    align-self: center;
}

Open in CodePenopen in new window

grid 第3种

.box {
    display: grid;
    justify-items: center;
}
.small {
    align-self: center;
}

Open in CodePenopen in new window

grid 第4种

.box {
    display: grid;
    align-items: center;
}
.small {
    justify-self: center;
}

Open in CodePenopen in new window