AskHandle

AskHandle Blog

Centering a DIV Like a Pro

September 25, 2025Annie Hayes3 min read

Centering a DIV Like a Pro

Learn how to center a div on your webpage effectively. We will guide you through the steps to ensure your div is positioned right in the center, irrespective of screen size or device.

Centering a div improves the aesthetics and user experience of your website. Let’s get started on making that div look sharp and centered!

Using CSS Flexbox

Can Flexbox help with layout issues? Yes! To center your div both horizontally and vertically with Flexbox, follow these steps:

First, set the parent element to act as a Flex container in your CSS:

css
1.parent {
2  display: flex;
3  justify-content: center;
4  align-items: center;
5  height: 100vh; /* This ensures it takes up the full viewport height */
6}

With justify-content: center;, the children, including your div, align in the middle of the container horizontally. Meanwhile, align-items: center; vertically centers the div.

Using CSS Grids

Is CSS Grid a good alternative? Absolutely! It offers a unique way to center your div. To use Grid, apply these styles to the parent container:

css
1.parent {
2  display: grid;
3  place-items: center;
4  height: 100vh; /* Again, full viewport height */
5}

Here, place-items: center; centers the div both horizontally and vertically with just one property.

The Classic Margin Auto

Prefer a classic method? The margin: auto; technique is a traditional way to center a div horizontally. Here’s how to do it:

css
1.center-div {
2  width: 50%; /* or your chosen width */
3  margin-left: auto;
4  margin-right: auto;
5}

This method only centers the div horizontally. To center it vertically too, you will need to set the position to absolute and add top and left properties combined with a transform.

Absolute Position and Transform

Want a more advanced technique? Use absolute positioning with a transform for a flashy centering method:

css
1.center-div {
2  position: absolute;
3  top: 50%;
4  left: 50%;
5  transform: translate(-50%, -50%);
6}

This places the div at half the height and width of the parent. The transform: translate(-50%, -50%); nudges it back to the center, ensuring it lands perfectly.

Test your centering on different devices to ensure a consistent appearance across monitors, tablets, and smartphones.