垂直水平居中的实现方法一直是前端面试官的钟情问题,我整理了一下几种常见的垂直水平居中的方法,希望对大家有所帮助。话不多说,上干货 !!!
还有一点需要大家的注意,我们这里的垂直水平居中针对的是width和height不确定的情况下。当width和height知道的情况下,通过计算利用margin之类的也可以实现,但那不是我们讨论的范围
method 1
第一种方法是利用grid布局中的容器属性来实现
HTML
<body>
<div class="box">
<p>Hello,我要实现垂直水平居中</p>
</div>
</body>
css
.box {
width: 500px;
height: 500px;
background-color: rgba(255, 0, 0, 0.6);
display: grid;
align-items: center;
justify-items: center
}
.box>p {
background-color: blue;
}
method 2
另一种利用grid的容器属性的实现方法
HTML
<body>
<div class="box">
<p>Hello,我要实现垂直水平居中</p>
</div>
</body>
css
.box {
width: 500px;
height: 500px;
background-color: rgba(255, 0, 0, 0.6);
display: grid;
align-items:center;
justify-content:center;
}
.box>p {
background-color: blue;
}
method 3
当grid布局下,我们利用Margin也可以实现垂直居中布局,这种方式简单理解就是,元素的margin将父元素的多余可用空间给占满了。
HTML同上
css
.box {
width: 500px;
height: 500px;
background-color: rgba(255, 0, 0, 0.6);
display: grid;
}
.box>p {
background-color: blue;
margin:auto;
}
method 4
将布局换为flex后,也是同样的效果。
- 方式一
.box {
width: 500px;
height: 500px;
background-color: rgba(255, 0, 0, 0.6);
display: flex;
}
.box>p {
background-color: blue;
margin:auto;
}
- 方式二
.box {
width: 500px;
height: 500px;
background-color: rgba(255, 0, 0, 0.6);
display: flex;
align-items:center;
justify-content:center;
}
.box>p {
background-color: blue;
}
method 5
利用绝对定位实现元素的垂直水平居中。但这种方式会有一些问题,即我们在使用绝对定位时,是绝对定位元素的外边距相对于参考元素边框内壁的偏移,即考虑子元素的margin影响,但transform不考虑margin的影响,这就导致我们最终得出的结果并不是在最中心的。因此我们要将子元素的margin设为0。
css如下
.box {
width: 500px;
height: 500px;
background-color: rgba(255, 0, 0, 0.6);
position:relative;
}
.box>p {
background-color: blue;
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
margin:0;
}
method 6
利用vertical-align与text-align的方式实现。我们在学习常见样式时,遇到过一个样式叫做vertical-align,作用就是设置inline、inline-block、table-cell的元素垂直对齐方式。然后配合上text-align即可实现。但是这最终实现的效果是文字上的居中,如果要实现如上的效果,还需要将他的类型设置为inline-block。
.box {
width: 500px;
height: 500px;
background-color: rgba(255, 0, 0, 0.6);
display:table-cell;
vertical-align:middle;
text-align:center;
}
.box>p {
background-color: blue;
display:inline-block;
}
method 7
设置行高的方式
.box {
width: 500px;
height: 500px;
background-color: rgba(255, 0, 0, 0.6);
text-align: center;
}
.box>p {
background-color: blue;
display: inline-block;
}
.box::after {
content: 'ssssg';
line-height: 500px;
}
method 8
这种方式已经废弃,因为他不得不设置子元素的宽和高,违背了我们的初衷。这种方法简单理解就是绝对定位元素设置他的偏移量相对于父元素的边框内壁都为0,即将他的上下左右margin分别与父元素的边框内壁重合,使得他的内容只能在中间。
.box {
width: 500px;
height: 500px;
background-color: rgba(255, 0, 0, 0.6);
position:relative;
}
.box>p {
position:absolute;
background-color: blue;
width:250px;
height:30px;
top:0;
bottom:0;
left:0;
right:0;
margin:auto;
}