CSS元素水平/垂直居中的几种方式

291 阅读1分钟

前言

本文整理了css块级元素和行内元素水平和垂直居中的几种方式,如果对答案有不一样见解的同学欢迎评论区补充讨论,当然有问题,也欢迎在评论区指出。

一、HTML 代码部分

<!-- 块级元素 -->
<div class="parent">
   <div class="child">我是一段文字,我想要居中</div>
</div>
<!-- 行内元素 -->
<div class="parent">
   <span class="child">我是一段文字,我想要居中</span>
</div>
<style>
*{
    margin: 0;
    padding: 0;
}
.parent{
    width: 100vw;
    height: 100vh;
    background: #88D6E9;
}
</style>

二、水平居中

1、text-align: center(块级、行内元素通用)

行内元素
.parent {
   text-align: center;
}

2、flex弹性布局justify-content(块级、行内元素通用)

.parent{
    display: flex;
    justify-content: center;
}

3、绝对定位+偏移,父绝子相(通用)

.child{
    position: absolute;
    left: 50%;
    transform: translate(-50%,0);
}
.child{
    position: absolute;
    left: 50%;
    width: 400px;
    margin-left: -200px;
}

4、margin: auto(只适合块级元素,因为行内元素,不能设置margin: 0 auto;)

.child{
    //需要设置块级元素宽度
    width: 400px;
    margin: 0 auto;
}

三、垂直居中

1、line-height(通用)

.child{
    line-height: 100vh;
}

2、flex弹性布局align-items(通用)

.parent{
    display: flex;
    align-items: center;
}

3、绝对定位+偏移,父绝子相(通用)同水平居中类似

4、margin: auto 0(只适合块级元素,因为行内元素,不能设置margin: auto 0;)

.child {
    height: 40px;
    position: absolute;
    top: 0;
    bottom: 0;
    margin: auto 0;
}

5、伪元素::before(通用)

.parent::before {
    content: '';
    height: 100%;
    display: inline-block;
    vertical-align: middle;
}
.child{
    display: inline-block;
    vertical-align: middle;
}

6、display: table-cell(通用)

.parent {
    display: table;
}
.child {
    display: table-cell;
    vertical-align: middle;
}

总结

觉得写得好的,对你有帮助的,可以分享给身边人,知识越分享越多,千万不要吝啬呀

后续更新css两栏布局方法,请关注我,整理好,分享给你们,我们一起学前端