一、水平居中
1、如果被设置元素为文本、图片时,可以给父元素添加
text-align:center;
注:当行文本可设置行高=容器高实现垂直居中
2、定宽块状元素
margin:0 auto;
3、不定宽块状元素在父元素水平居中
3.1 父元素 text-align:center;
子元素 display:inline-block;
注:转化为内联块状元素后中级不能添加空格,会占位
3.2 父元素 display:table;
margin:0 auto;
二、绝对居中问题(即水平垂直均居中)
1、定宽高元素绝对居
.box{
width:100px;
height:100px;
position:fixed;
left:50%;
right:50%;
margin-lefe:-50px;/* -0.5*width */
margin-top:-50px;/* -0.5*height */
}
2、不定宽高元素在整个窗口中居中
.box{
position:fixed;
left:50%;
right:50%;
margin:auto;
}
3、不定宽高(父元素)
第一种方法
父元素 position:relative;
子元素 position:absoulte;
left:0;
right:0;
bottom:0;
top:0;
margin: auto;
第二种方法
父元素 display:table-cell;
text-align:center;
vertical-align:middle;
第四种方法:弹性盒子
html,body{height:100%}
body{
display:flex;
justify-content:center;
align-items:center;
}
第五种方法:定位+位移
.box{
position:fixed;
top:50%;
left:50%;
transform:translate(-50%,-50%);
}/*在屏幕中居中*/
父元素 position:relative;
子元素 position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);