css实现水平垂直居中对齐
仅居中元素固定宽高适用
- absolute + 负margin
- absolute + margin auto
- absolute + calc
居中元素不定宽高
- absolute + transform
- lineheight
- css-table
- flex
- grid
仅居中元素固定宽高适用
1、absolute + 负margin
绝对定位的百分比是相对于父元素的宽高,通过这个特性可以让子元素的居中显示,但绝对定位是基于子元素的左上角,期望的效果是子元素的中心居中显示
为了修正这个问题,可以借助外边距的负值,负的外边距可以让元素向相反方向定位,通过指定子元素的外边距为子元素宽度一半的负值,就可以让子元素居中了,css代码如下
.dbox { //父元素
border: 1px solid red;
position: relative;
width: 300px;
height: 300px;
}
.box { //子元素
width: 100px;
height: 100px;
background: skyblue;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
position: absolute;
}
2、absolute + margin auto
这种方式通过设置各个方向的距离都是0,此时再讲margin设为auto,就可以在各个方向上居中了
.dbox {
border: 1px solid red;
position: relative;
width: 300px;
height: 300px;
}
.box {
width: 100px;
height: 100px;
background: skyblue;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
3、absolute + calc
css3带来了计算属性,既然top的百分比是基于元素的左上角,那么在减去宽度的一半就好了,代码如下
.dbox {
border: 1px solid red;
position: relative;
width: 300px;
height: 300px;
}
.box {
width: 100px;
height: 100px;
background: skyblue;
position: absolute;
top: calc(50% - 50px);
left: calc(50% - 50px);
}
居中元素不定宽高
1、absolute + transform
修复绝对定位的问题,还可以使用css3新增的transform,transform的translate属性也可以设置百分比,其是相对于自身的宽和高,所以可以讲translate设置为-50%,就可以做到居中了,代码如下
.dbox {
border: 1px solid red;
position: relative;
width: 300px;
height: 300px;
}
.box {
background: skyblue;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
2、lineheight
把box设置为行内元素,通过text-align就可以做到水平居中,通过vertical-align也可以在垂直方向做到居中,代码如下
.dbox {
border: 1px solid red;
width: 300px;
height: 300px;
line-height: 300px;
text-align: center;
font-size: 0px;
}
.box {
background: skyblue;
font-size: 16px;
display: inline-block;
vertical-align: middle;
line-height: initial;
text-align: left; /* 修正文字 */
}
3、css-table
css新增的table属性,可以让我们把普通元素,变为table元素的现实效果,通过这个特性也可以实现水平垂直居中
.dbox {
border: 1px solid red;
width: 300px;
height: 300px;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.box {
background: skyblue;
display: inline-block;
}
4、flex
目前在移动端已经完全可以使用flex了,PC端需要看自己业务的兼容性情况
.dbox {
border: 1px solid red;
width: 300px;
height: 300px;
display: flex;
justify-content: center;
align-items: center;
}
.box {
background: skyblue;
}
5、grid
css新出的网格布局,通过grid也可以实现水平垂直居中
.dbox {
border: 1px solid red;
width: 300px;
height: 300px;
display: grid;
}
.box {
background: skyblue;
justify-self: center;
}
总结
- PC端有兼容性要求,宽高固定,推荐absolute + 负margin
- PC端有兼容要求,宽高不固定,推荐css-table
- PC端无兼容性要求,推荐flex
- 移动端推荐使用flex