Center a div like a pro!

Center a div like a pro!

There are multiple ways to center a div using CSS and in this short post I mention a few of them.

Before we continue, make sure to create a free account on DoTenX, create a project so you can apply these methods there. The benefit of doing that is not only you learn a few tips about CSS, you familiarise with a tool you can use to visually build applications and publish them immediately.

After creating your project, click on UI builder and make sure you switch to advanced mode.


Now, let's get back to centering our divs. Some of the most common ways to center a div include using the margin: auto property, using the text-align: center property, using the display: flex property, and using the display: grid property.

To center a div (a Box on DoTenX) using the margin: auto property, you simply need to add the margin: auto property to the div's style. For example, the following code centers a div with the class "centered":

.centered {
  margin: auto;
}

You can also center a div using the text-align: center property. All you needs to do is to add the text-align: center property to the div's style. This property centers all the content within the div, including text and other inline elements. For example, the following code centers the text and other inline elements within a div with the class "centered":

.centered {
  text-align: center;
}

Another approach is to use the display: flex property. This property allows you to use the justify-content: center property to center the div horizontally, and the align-items: center property to center the div vertically.

For example, this code centers a div with the class centered both horizontally and vertically:

.centered {
  display: flex;
  justify-content: center;
  align-items: center;
}

Finally, you can use the display: grid property to center a div. This property allows you to use the justify-items: center property to center the div horizontally, and the align-items: center property to center the div vertically.

For example, the following code centers a div with the class centered both horizontally and vertically:

.centered {
  display: grid;
  justify-items: center;
  align-items: center;
}

Now that you know multiple ways to center a div, try it on actual project with your free account on DoTenX.