css绝对定位居中的实现方法有很多,下面将给大家介绍css绝对定位居中:
使用子绝父相的方式实现水平垂直居中。父元素设置position: relative
。子元素设置 position: absolute
;
.father {
position: relative;()
width: 500px;
height: 500px;
background-color: pink;
}
方法1:子绝夫相+margin
使用范围:让固定宽度和高度小盒子居中
.son {
position: absolute;
left: 50%;
top: 50%;
margin-top: -50px;(自身高度的一半)
margin-left: -50px;(自身宽度的一半)
width: 100px;
height: 100px;
background-color: red;
}
方法二:子绝夫相+2d转换
使用范围:不固定宽度和高度小盒子居中
.son {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%); (50%为自身尺寸的一半 )
width: 100px;
height: 100px;
background-color: green;
}
方法三:子绝夫相+margin:auto;
使用margin居中
.son {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
width: 100px;
height: 100px;
background-color: blue;
}