.jpg)
# 一、水平居中
# 1.行内元素水平居中
如果父元素是block,直接给父元素text-align: center ,如果不是{display:block,text-align: center}
# 2.块级元素的水平居中
- 定宽度
{width:100px;height:100px;margin:0 auto} - 不定宽度
father{text-align:center}
son{display: inline/inline-block} - 使用定位
- 定宽度
.father{ height:100px;width:100px; position:relative } .son{ height:50px;width:50px; position:absolute; left:50%; margin-left: -50px; }- 不定宽度
.son{ height:50px; position:absolute; left:50%; transform:translateX(-50%) }- 定不定宽都行
.father{ display:flex; justify-content:center }
# 垂直居中
# 1.行内元素垂直居中
//单行行内元素
.father{
width:100px;
height:300px
}
.son{
line-height:300px
}
//多行行内元素
.father{
width:100px;
height:100px;
display:table-cell;
vertical-align:middle
}
# 2.块级元素垂直居中
- 固定高度
.father{
width:100px;
height:100px;
position:relative;
}
.son{
position:absolute;
top:50%;
margin-top:-50px
}
- 不固定高度
.father{
width:100px;
height:100px;
position:relative;
}
.son{
position:absolute;
top:50%;
transform:translateY(-50%)
}
- 定不定高都行
.father{
display:flex;
align-items:center
}
# 水平垂直居中
# 已知宽高
.container{
width:500px;
height:300px;
position:relative
}
.center{
width:100px;
height:100px;
position:absolute;
top:0;right:0;bottom:0;left:0;
margin:auto
}
.container{
width:500px;
height:300px;
position:relative
}
.center{
width:100px;
height:100px;
position:absolute;
left:50%;
top:50%;
margin-left:-50px; //相对自身
margin-top:-50px
}
# 未知宽高
.center{
position:absolute;
left:50%;
top:50%;
transform:translate(-50%,-50%)//自己的
}
.container{
display:flex;
justify-content:center;
align-items:center;
}