Centering in HTML

There are several ways to center text and HTML elements, depending on whether the content is text, an inline element, or a block-level element.

Here are the most common and effective ways to handle centering in your HTML layout.

How to Center Text

The simplest way to center text within an element (like a div or p) is to use the text-align property with the value center.

This works for all inline-level elements such as text, images, and links.

View Output

How to Center a Block-Level Element

Block-level elements (like a div) can be centered horizontally by setting their margin property to auto and specifying a width.

Without a specified width, a block element normally takes up the full width of its container, so you won't see it centered unless it's smaller than its parent.

View Output

How to Center an Image

To center an image, you can either wrap it in a div with text-align: center, or convert the image to a block-level element using the display property set to block and then apply margin: auto.

View Output

How to Center Vertically and Horizontally using Flexbox

Flexbox is a modern CSS layout tool that makes centering incredibly easy. By making the parent container a "flex container" (using display: flex), you can center its children both horizontally (using justify-content) and vertically (using align-items).

This is generally the preferred way for modern web design because it handles vertical centering much better than traditional methods.

View Output

Using text-align: center as a quick fix is great, but Flexbox is much more robust for complex layouts and responsive designs.