怎么让一个div水平垂直居中

<div class="parent">
    <div class="child"></div>
</div>
复制代码

1)使用position + transform,不定宽高时

.parent{
    position: relative;
}
.child{
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
}
复制代码

2)使用position + transform,有宽高时

.parent{
    position: relative;
}
.child{
    width: 100px;
    height: 100px;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -50px;
    margin-top: -50px;
}
复制代码

3)使用flex

.parent{
    display: flex;
    align-items: center;
    justify-content: center;
}
复制代码

或者

.parent{
    display: flex;
    align-items: center;
}
.child{
    margin: 0 auto;
}
复制代码

或者

.parent{
    display: flex;
}
.child{
    margin: auto;
}
复制代码

4)使用position

.parent{
    position: relative;
}
.child{
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}
复制代码

5)使用grid

.parent{
    display: grid;
}
.child{
    justify-self: center;
    align-self: center;
}
复制代码

6)使用table

.parent{
    display: table;
}
.child{
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}
复制代码

或者

.parent {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.child {
    display: inline-block;
}
复制代码

7)使用伪类

.parent{
    font-size: 0;
    text-align: center;
}
.parent::before {
    content: "";
    display: inline-block;
    width: 0;
    height: 100%;
    vertical-align: middle;
}
.child{
    display: inline-block;
    vertical-align: middle;
}

猜你喜欢

转载自blog.csdn.net/weixin_44197906/article/details/105505187
今日推荐