DIV垂直水平居中

方法一:使用定位的方法
.parent {
width: 300px;
height: 200px;
border: 1px solid red;
position:relative;
}
.child {
width: 100px;
height: 100px;
border: 1px solid violet;
position:absolute;
top: 50%;
left:50%;
margin-top: -50px; /*这里是小盒子高的一半*/
margin-left: -50px; /*这里是小盒子宽的一半*/
}
使用定位方法,需要知道子元素的宽高,但是不需要知道父元素的宽高.1
方法二:利用定位及margin:auto实现 (实现原理是设置margin自动适应,然后设置定位的上下左右都为0,就如四边均衡受力从而实现盒子的居中;)
.parent {
width: 300px;
height: 200px;
border: 1px solid red;
position:relative;
}
.child {
width: 100px;
height: 100px;
border: 1px solid violet;
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}

浙公网安备 33010602011771号