There are many ways to implement CSS absolute positioning and centering. Below we will introduce to you four methods of CSS absolute positioning and centering.
1. Usage of mainstream CSS absolute positioning and centering with good compatibility:
.conter{
width:600px;height:400px;
position:absolute;left:50%;top:50%;
margin-top:-200px;/*高度的一半*/
margin-left:-300px;/*宽度的一半*/
}
Note: This method has an obvious shortcoming, which is that the size of the element needs to be known in advance. Otherwise, the adjustment of negative margin values cannot be accurate. At this time, it is often necessary to obtain it with the help of JS.
2. The emergence of CSS3 has led to a better solution, which is to use transform instead of margin. The percentage value of the translate offset in transform is relative to its own size. You can achieve CSS absolute positioning and centering like this:
.conter{
width:600px;height:400px;
position:absolute;left:50%;top:50%;
transform:translate(-50%,-50%);/*50%为自身尺寸的一半*/
}
3. margin:auto realizes the centering of absolutely positioned elements (0 position positioning for top, bottom, left, and right; margin:auto)
.conter{
width:600px;height:400px;
position:absolute;left:0;top:0;right:0;bottom:0;
margin:auto;/*有了这个就自动居中了*/
}