Text-align :center CSS horizontal center is the basic skills of front-end engineers, I often encounter the requirements of CSS horizontal center in the project, this tutorial will be used in my past 9 CSS horizontal center method summarized, but also convenient to use later when the review.

Tools/materials

CSS text-align:center

Methods/steps

Margin: 0 auto; Text-align: center The CSS is horizontally centered.

Margin: 0 auto; margin: 0 auto; margin: 0 auto; margin: 0 auto; Text-align: center”

2. Run display:flex to center the CSS horizontally.

As more and more flexboxes are compatible, CSS horizontal centralization via “display: Flex” is becoming more and more popular.

Display :flex to implement CSS horizontal centering is the parent element display:flex; flex-direction:column; And the child element align-self:center;

This works the same way as CSS vertical centring, except for flex direction, row(the default) and column.

3. Run the display:table-cell and margin-left command to center the CSS horizontally.

If the widths of both parent and child elements are determined, the display:table-cell and margin-left commands can be used to center the CSS horizontally.

When used, the parent element display:table-cell and the child element give half of the remaining width to the margin-left.

4. Use Position: Absolute to center the CSS horizontally.

This method applies to scenarios where the width of both parent and child elements is determined, just as the previous method does.

When used, the parent element position:absolute, and the child element gives a margin-left half of the remaining width.

5. Use width: fit-Content to center the CSS horizontally.

This ensures that CSS is horizontally centered even when the child element width is uncertain.

Margin: 0 auto; Text-align: center”

6. Run the display:inline-block and text-align:center commands to center the CSS horizontally.

Display :inline-block; display:inline-block; margin: 0 auto; Text-align: center”

7. Use position:relative, float:left, and margin-left to center the CSS horizontally.

CSS horizontal center is achieved by giving the parent style position:relative and the child style float:left and margin-left.

8. Center the CSS horizontally by hiding nodes +float.

We can do this by adding a hidden node and making it float:left so that the element is horizontally centered by the hidden node.

This method of adding hidden nodes also works with CSS vertically centered, but without floats.

9. Use Transform to center the CSS horizontally.

This is the least recommended method because the transform property behaves differently across browsers, causing some compatibility issues and is recommended only when the user’s browser is known.

Matters needing attention

CSS level 1, 3, and 4 have the best browser compatibility, while the others have more or less some browser compatibility deficiencies