css应用
使div垂直水平居中的几种方法
- 使用绝对定位+translate
.element {
width: 600px; height: 400px;
position: absolute; left: 50%; top: 50%;
margin-top: -200px; /* 高度的一半 */
margin-left: -300px; /* 宽度的一半 */
}
以前的浏览器可能会采用这种写法,但是前提是我们需要知道容器的具体宽度和高度,
后面浏览器支持了translate属性所以我们可以通过下面的写法来代替上面的这个
.element {
width: 600px; height: 400px;
position: absolute; left: 50%; top: 50%;
transform: translate(-50%, -50%); /* 50%为自身尺寸的一半 */
}
transform属性允许你平移缩放旋转等操作,而translate就是平移,50%是相对于自身容器来说的,也就是我们不需要事先知道容器的高度和宽度也可以实现水平垂直居中
2. 使用flex布局
flex布局目前基本浏览器都已支持,它实现水平垂直居中的方法也很简单,通过它的两个属性
.element-father{
display:flex;
align-items:center; //实现垂直居中
justify-content:center; //实现水平居中
}
我们只需要在外容器设置布局为弹性布局,再设置水平和垂直方向都垂直居中即可。