CSS achieves horizontal vertical center of div, and horizontal center of cssdiv
There are many solutions for implementing center. Here we will introduce the solutions for pure CSS to use absolute with margin.
1. Fixed div width and height
width: 400px;height: 200px;position: absolute;top: 50%;left: 50%;margin-top: -100px;margin-left: -200px;
Margin-top is-(height/2), and margin-left is-(width/2 ). Of course, you do not need to use margin, that is, top is calc (100%-height)/2, left is calc (100%-width)/2, but it is recommended that you do not use it without calc.
2. The div width and height are not fixed.
width: 50%;height: 50%;position: absolute;top: 0;right: 0;bottom: 0;left: 0;margin: auto;
Note: this applies to situations where the width and height need to be specified, such as using percentages or using js to dynamically modify them. Otherwise, it may be treated as 100%.
You can also use translate () instead of margin, as shown below:
width: 50%;height: 50%;position: absolute;top: 50%;left: 50%;transform: translateX(-50%) translateY(-50%);
3. CSS3 fixed width and high-level vertical center
Justify-content: center;/* sub-element horizontal center */align-items: center;/* sub-element vertical center */display:-webkit-flex;
Add the parent element to vertically center the child element horizontally.