元素居中
元素的水平和垂直居中:
来自一个野蛮生长的前端小白的成长记录开始咯,先从元素居中开始:
(1)元素的宽高固定(元素百分比偏移和margin加偏移量)
.parent{
position: relative;
}
.child{
position: absolute;
width: 固定;
height: 固定;
top: 50%;
left: 50%;
margin-top: -50%*高度;
margin-left: -50%*宽度;
}
适用于所有浏览器
(2)元素的宽高固定(margin的auto)
.parent{
position: relative;
}
.child{
position: absolute;
width: 固定;
height: 固定;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
适用于所有浏览器
(3)使用transform属性
.parent{
position: relative;
}
.child{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
要考虑transform兼容性
(4)使用table
.parent{
display: table-cell;
vertical-align: middle;
text-align: center;
}
.child{
display: inline-block;
}
要考虑table兼容性
(5)使用flex
.parent{
display: flex;
justify-content: center;
align-items: center;
}
要考虑flex兼容性问题