How does CSS achieve horizontal and vertical centering? 4 very commonly used methods in work

*How does CSS achieve horizontal and vertical centering?

**
1. Use the "child-to-parent phase" in positioning [The core code is that the margin-top and margin-left added to the child box are respectively equal to the negative half of its own height and width]
PS: Disadvantages: need to be advanced Know the size of the element. If you don't know the element size, you need to get it by JS at this time.
The core code is that the margin-top and margin-left added to the child box are respectively equal to the negative half of its own height and width
2. Use margin: auto in positioning, of course, also under absolute positioning
Insert picture description here
3. Absolute positioning -bit offset
Insert picture description here

4. CSS3.0 elastic layout
Elastic layout ① Add elastic elements to the body (parent box) display: flex;
align-items: center; / The element that defines the body is vertically centered (
/Main axis is centered-the main axis is the x axis by default) /justify- content: center; / The element that defines the body is centered horizontally //The side axis is centered-the main axis is the y axis by default)

Insert picture description here

Note that it must be added to the parent box with a flexible element display: flex, which results in the vertical centering of the child box :
Insert picture description here

Guess you like

Origin blog.csdn.net/zhongheng310/article/details/114119101