行内元素实现水平垂直居中:
text-align: center;(text-align: center只能实现文本的垂直居中)
line-height: 50px;(line-height不能实现多行文本的垂直居中)
padding:50px;(不固定高度的垂直居中 通过设置padding实现)
使用display设置为table,配合样式vertical-align设置为middle来实现,如下:
父元素{
display:table;
}
子元素{
display:table-cell;
vertical-align:middle;
}
块级元素实现水平垂直居中:
第一种方式:使用弹性盒模型实现水平垂直居中
display: flex;
justify-content: center;
align-items: center;
第二种方式:采取绝对定位配合margin的方式实现(这种方式有缺陷 需要知道固定的宽度和高度才行)
position: absolute;
left:50%;
top:50%;
margin-left: -50px;(高度设置了100px,margin-left就是宽度的一半)
margin-top: -50px;(宽度也设置了100px,margin-top就是高度的一半)
第三种方式:可以采取借助css3的变形属性transform来实现的方式实现
position: absolute;
left:50%;
top:50%;
transform: translate(-50%,50%);(在当前位置偏移自身宽高的一半)
第四种方式:需要盒子有宽高,但是不需要去计算偏移盒子的宽高
position: absolute;
left:0;
top:0;
right:0;
bottom:0;
margin:auto;
height:100px;
width:100px;