CSS垂直水平居中的方式

152 阅读2分钟

CSS垂直水平居中的方式

1、flex

大家的第一反应,可能就是 flex 了。因为它的写法够简单直观,兼容性也没什么问题。是手机端居中方式的首选。

<div class="wrapper flex-center">
    <p>horizontal and vertical</p>
</div>
<style>
.wrapper {
    width: 300px;
    height: 300px;
    border: 1px solid #ccc;
}

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

//设置弹性子元素
.child{
	margin:auto;
}
</style>

利用到了 2 个关键属性:justify-content 和 align-items,都设置为 center,即可实现居中。

需要注意的是,一定要把这里的 flex-center 挂在父级元素,才能使得其中 唯一的 子元素居中。

2、flex + margin

这是 flex 方法的变种。父级元素设置 flex,子元素设置 margin: auto;。可以理解为子元素被四周的 margin “挤” 到了中间。

    <p>horizontal and vertical</p>
</div>
<style>
.wrapper {
    width: 300px;
    height: 300px;
    border: 1px solid #ccc;

    display: flex;
}

.wrapper > p {
    margin: auto;
}
</style>

3、transform + absolute

这个组合,常用于图片的居中显示。

    <img src="test.png">
</div>
<style>
.wrapper {
    width: 300px;
    height: 300px;
    border: 1px solid #ccc;
    position: relative;
}

.wrapper > img {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}
</style>

当然,也可以将父元素 wrapper 的相对定位,移入子元素 img 中,替换掉绝对定位。效果是一样的。

4、table-cell

利用 table 的单元格居中效果展示。与 flex 一样,需要写在父级元素上。

<div class="wrapper">
    <p>horizontal and vertical</p>
</div>
<style>
.wrapper {
    width: 300px;
    height: 300px;
    border: 1px solid #ccc;

    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
</style>

5、absolute + 四个方向的值相等

使用绝对定位布局,设置 margin:auto;,并设置 top、left、right、bottom 的 值相等即可(不一定要都是 0)。

<div class="wrapper">
    <p>horizontal and vertical</p>
</div>
<style>
.wrapper {
    width: 300px;
    height: 300px;
    border: 1px solid #ccc;
    position: relative;
}

.wrapper > p {
    width: 170px;
    height: 20px;
    margin: auto;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}
</style>