Centering an element in your web layout is a challenge that has always frustrated designers. It hasn’t always been easy to do, but many designs require central positioning. Fortunately, modern CSS now has good support for centering.

Learn how to center a div horizontally and vertically using Flexbox, CSS Grid, and CSS positioning.

A red square in the middle of a web page with Chrome Dev Tools showing the HTML and CSS

A Simple HTML File to Practice Centering

The following examples all use a minimal HTML document to demonstrate centering with CSS. Use this markup and vary the CSS according to each section to see how these properties behave.

Using Flexbox to Center a Div Element

You’ll need tounderstand the basics of Flexboxbefore using it to center a div element. Fortunately, Flexbox follows a simple approach, which is why it’s the most widely used. It provides a flexible layout model that makes it easy to align and distribute space among items in a container, making it ideal for centering elements.

Use the following CSS to achieve centering with Flexbox.

Viewing the result inGoogle Chrome’s DevTools, you can see how the two properties control alignment along each axis:

Using CSS Grid to Center a Div Element

Using CSS Gridto center an element is another effective method, offering precise control over layout and alignment.

In this case, a single property controls the central placement of the div on your page:

A blue square in the middle of a web page with Chrome Dev Tools showing the HTML and CSS

Using CSS Positioning to Center a Div Element

Touse the CSS position propertyto center a div, you also need tounderstand how CSS transforms with transitions work. Here’s a step-by-step guide with an example.

This method works by first centering the element’s top corner, then moving it relatively by half of its width and half its height.

A green square in the middle of a web page with Chrome Dev Tools showing the HTML and CSS

Flexbox, CSS Grid, and CSS positioning are powerful tools you can use to center elements on a web page. With Flexbox, you can center both horizontally and vertically with just a few lines of code. CSS Grid provides powerful alignment in two dimensions, and you can use CSS positioning to center an element relative to its parent container.

With these techniques, you can ensure that your web pages look clean and professional.