子盒子在父盒子中水平垂直居中

子盒子在父盒子中水平垂直居中的几种实现方式。

方式一:margin;

HTML:

<!-- 以下样式全为此结构 -->
<div class="father">
    <div class="child"></div>
</div>

CSS:

.father{
    width: 400px;
    height: 400px;
}
.child{
    width: 100px;
    height: 100px;
    margin: 150px auto;
}

方式二:display: table-cell;

.father{
    display: table-cell;
    width: 400px;
    height: 400px;
    vertical-align: middle;
    text-align: center;
}
.child{
    display: inline-block;
    vertical-align: middle;
}

方式三:position + margin;

CSS:

.father{
    position: relative;
    width: 400px;
    height: 400px;
}
.child{
    position: absolute;
    top: 50%;
    left: 50%;
    width: 100px;
    height: 100px;
    margin-left: -50px;
    margin-top: -50px;
}

方式四:position + transform;

CSS:

.father{
    position: relative;
    width: 400px;
    height: 400px;
}
.child{
    position: absolute;
    top: 50%;
    left: 50%;
    width: 100px;
    height: 100px;
    transform: translate(-50%,-50%);
}

方式五:display: flex;

CSS:

.father{
    display: flex;
    justify-content: center;
    align-items: center;
    width: 400px;
    height: 400px;
}
.child{
    width: 100px;
    height: 100px;
}

学习笔记,根据自己理解整理,不对的地方望指正,感谢!

猜你喜欢

转载自blog.csdn.net/username_xu/article/details/81536356