1、flex
使用flex布局,让居中元素的父元素为flex属性,让它在水平的主轴(main axis)和垂直的交叉轴(cross axis)居中就好
html:
<div class="father">
<div class="son"></div>
</div>
css:
*{
margin:0;
padding:0;
}
.father{
width:500px;
height:500px;
background-color:bule;
display:flex;//父元素设置flex属性
justify-content:center;//水平居中
align-items:center;//垂直居中
}
.son{
width:100px;
height:100px;
background-color:red;
}
flex水平居中:justify-content:center
flex垂直居中:align-items:center
2、使用绝对定位实现
父元素相对定位,子元素绝对定位
html同上
css:
.father{
width:500px;
height:500px;
background-color:bule;
position:relative;
}
.son{
width:100px;
height:100px;
background-color:red;
positon:absolute;
top:0;
bottom:0;
left:0;
right:0;
margin:auto;
}
为子元素top: 0; left: 0; bottom: 0; right: 0;将给浏览器重新分配一个边界框,此时该块块将填充其父元素的所有可用空间,所以margin 垂直水平方向上有了可分配的空间。再设置margin 垂直方向上下为auto,即可实现垂直水平居中。(注意宽度高度得设置)。
如果已知高度和宽度(高度必须设置,宽度可跟随父级一致)
则css:
p{
width:100px;
height:100px;
background:red;
position:absolute;
top:50%;
left:50%;
margin-left:-50px;
margin-top:-50px;
}
3、position+transform实现
html:同上
css:
.father {
background:bule;
height:500px;
position: relative;
}
.son{
position: absolute;
left:50%;
top:50%;//50%并不是居中的,因为它是以元素的上border为标准移动50%的
transform:translate(-50%,-50%)//所以我们需要像上移动元素自身高度一半儿的距离,前-50%表示垂直,后——50%表示居中
}
4、对单行文本的行内元素
line-height控制垂直居中,text-align控制行内水平居中
html:
<div>
<span>我是行内</span>
</div>
css:
div{
width:300px;
height:100px;
background:pink;
text-align:center;
line-height:100px;//设置的和行高一样
}
span{
background:blue;
}
如果是多行文本,则水平不变,垂直用display:table-cell;vertical-align:middle
css:
div{
width:300px;
height:100px;
background:pink;
text-align:center;
display:table-cell;
vertical-align:middle;
}
span{
background:blue;
}