元素 水平垂直居中 的几种的方法
对于行内元素:
设置行高为height,实现垂直居中
text-align:center;
line-height:30px;
对于块级元素:
方法一:
使用绝对定位【已知子元素宽高的情况下使用】
#parent{
position:relative;
}
#child{
position:absolute;
left:50%;
top:50%;
margin-top:-子元素的高/2;
margin-left:-子元素的宽/2;
}
方法二:
使用绝对定位,margin自适应进行居中:
#parent{
position:relative;
}
#child{
position:absolute;
top:0;
right:0;
bottom:0;
left:0;
margin:auto;
}
方法三:
使用绝对定位+transform
#parent{
position:relative;
}
#child{
position:absolute;
left:50%;
top:50%;
transform:translate(-50%,-50%);
}
方法四:
使用弹性盒子flex布局:
#parent{
display:flex;
justify-content:center;
align-items:center;
}