How to Center An Element Horizontally in CSS?

We can center any CSS element easily by using flex property. It was very hard to align items before the invention of CSS flex property. In 2022, you can center an item horizontally with just 2 lines of code by converting the item into a flex.

Example 1: Horizontally Center a Div Element

Here, the main div element with the class name “flex” is centered both horizontally and vertically. So, their child elements will also be centered automatically.

HTML

CSS

Example 2: Center Any Inline Element

It is easy to center a block-level element, but inline elements are very hard to center as we don’t know how much space they occupy and what their width is. So, we should convert an inline element into a block element and set the text-align property to center.

HTML

CSS

Example 3: Center An Inline Element Using Auto Margin Property

If you know the width of the element, or if you have no problems in setting the width of the inline element, you can center it by setting a custom width and adjusting the margin property.

HTML

CSS

Example 4: Center Div Element Using Auto Margin Property

We can center a div element by changing the margin property. The div element is a block-level element and so it is easy to center it horizontally.

HTML

CSS

Conclusion

I suggest you use flex property for centering any div element. For inline elements, you can use any of the above two methods.