There are many ways to implement horizontal and vertical centralization of CSS. Here are some of the differences:

Absolute + negative margin: this method is commonly used. The disadvantage is to know the width and height of the child elements.

Parent: position: relative;

Position: Absolute; top: 50%; left: 50%; Margin-left: – half the width; Margin-top: – Half the width;

2. Absolute +margin auto: The disadvantage is to know the width and height of the child elements.

Parent: position: relative;

Position: Absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto;

3. Flex: Just parent styles. Mobile terminal can be used, PC depends on the compatibility of their own services.

Parent: display: flex; justify-content: center; align-items: center;

4. Absolute + Transform: This method is compatible with Translate2D.

Parent: position: relative;

Position: Absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);

Absolute +calc: calc-dependent compatibility, the disadvantage is to know the width and height of the child elements.

Parent: position: relative;

Position: Absolute; Top: calc(50% – half width); Left: calc(50% – half width);

6. Lineheight: Use the center attribute of the inline element to center the horizontal direction through text-align, and vertical-align to center the vertical direction.

Parent: line-height: the height of the parent; text-align:center; font-size:0px; Font-size: 16px; display: inline-block; vertical-align: middle; line-height: intial; text-align: left;

7. Css-table: The table property of the CSS is used for good compatibility.

Parent: display: table-cell; text-align: center; vertical-align: middle;

Display: inline-block;

The following are not recommended, but can be done:

8. Table: The DOM structure code is too redundant and is not the correct use of table.

Text-align: center; text-align: center;

Display: inline-block;

9. Grid: Not recommended because it is not as compatible as Flex.

Parent: display: grid;

Child: align – self: center; justify-self: center;

10. Writing-mode: you can change the display direction of the text, you can change the vertical direction, but it will be too much code to use in the horizontal vertical center of div, which is a bit troublesome. It’s a bit complicated to implement and understand. Is not recommended.

They melody ~ ~

That’s about it. I’m used to using Flex.