**
CSS/CSS3实现水平垂直居中
**
前端页面中元素的水平垂直是比较常见的,下面来写几种css/css3实现的未知宽高元素的水平和垂直居中的写法。
第一种 css3的transform
.father{
/*设置元素相对定位*/
position: relative;
}
.son{
/*设置元素绝对定位*/
position:absolute;
/*top 50%*/
top: 50%;
/*left 50%*/
left: 50%;
/*css3 transform 实现*/
transform: translate(-50%, -50%);
}
第二种 flex弹性盒子布局
.father{
/*弹性盒模型*/
display:flex;
/*主轴居中对齐*/
justify-content: center;
/*侧轴居中对齐*/
align-items: center;
}
第三种 flex+margin:auto
.father{
/*弹性盒模型*/
display: flex;
}
.son{
margin: auto;
}
第四种 display的table-cell
在父元素设置text-align和vertical-align,并将父元素设置为table-cell元素,子元素设置为inline-block元素
.father{
/*让元素渲染为表格单元格*/
display:table-cell;
/*设置文本水平居中*/
text-align:center;
/*设置文本垂直居中*/
vertical-align:middle;
}
.son{
display: inline-block;
}
第五种 绝对定位配合margin
利用绝对定位元素的盒模型特性,在偏移属性为确定值的基础上,设置margin:auto
.father{
/*设置元素相对定位*/
position: relative;
}
.son{
/*设置元素绝对定位*/
position:absolute;
left:0;
right:0;
top:0;
bottom:0;
margin:auto;
}
第六种 grid网格布局
[注意]IE10-浏览器不支持
.father{
display: grid;
}
.son{
align-self: center;
justify-self: center;
}
/*第二种*/
.father{
display: grid;
align-content: center;
justify-content: center;
}
第七种 水平对齐+行高
实现单行文本水平垂直居中
.father{
text-align: center;
line-height: 100px;
}