问题网址 : http://bbs.daxiangclass.com/?thread-163.htm
如何垂直居中一个浮动元素?
方法一: 已经知道元素高宽
// 子盒子
#div1{
width:200px;
height:200px;
position: absolute; //父元素需要相对定位
top: 50%;
left: 50%;
margin-top:-100px ; //二分之一的height,width
margin-left: -100px;
}
未知父元素高宽
//子盒子
#div1{
width: 200px;
height: 200px;
margin:auto;
position: absolute; //父元素需要相对定位
left: 0;
top: 0;
right: 0;
bottom: 0;
background: red;
}
flex使盒子居中
// 父盒子
.da{
width: 500px;
height: 500px;
background: green;
display: flex; // 使用flex
align-items: center; // 上下居中
justify-content: center; // 左右居中
}
css3中的新属性transform实现盒子居中
.da{
/*父盒子*/
width: 500px;
height: 500px;
background: green;
position: relative;
}
#er{
/*我是子盒子我要居中*/
width: 200px;
height: 200px;
background: red;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
利用css3的新增属性table-cell, vertical-align:middle;
.da{
/*父盒子*/
width: 500px;
height: 500px;
background: green;
display: table-cell;
vertical-align: middle;
}
#er{
/*我是子盒子我要居中*/
width: 200px;
height: 200px;
background: red;
margin: auto;
}