Skip to content

How to centre align a div using CSS

How to centre align a div using CSS

In this article we will be seeing multiple ways to centre align a div. This is something that we need to do like when we there a loader that we need to add or a login section or any other use case.

Centre align a div using margin property

To center align a div, you can use the following CSS:

div {
  margin: 0 auto;
  text-align: center;
}

The margin: 0 auto; rule will center the div horizontally by setting the left and right margins to “auto”. The text-align: center; rule will center the contents of the div vertically. You can adjust the width of the div as needed.

Center align a div using flexbox

To center align a div using flexbox, you can use the following CSS:

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

Here, the container class is the parent element of the div that you want to center. The display: flex; rule sets the display property of the container element to flex. The justify-content: center; rule centers the child elements of the container element along the horizontal axis. The align-items: center; rule centers the child elements of the container element along the vertical axis.

Then, you can simply add your div element inside the container, like this:

<div class="container">
  <section>Content to be centered</section>
</div>

This will center your div element both horizontally and vertically inside the container. You can adjust the styles as needed to get the desired result.

Center align a div using grid

To center align a div using CSS grid, you can use the following CSS:

.container {
  display: grid;
  place-items: center;
}

Here, the container class is the parent element of the div that you want to center. The display: grid; rule sets the display property of the container element to grid. The place-items: center; rule centers the child elements of the container element both horizontally and vertically.

Then, you can simply add your div element inside the container, like this:

<div class="container">
  <div>Content to be centered</div>
</div>

This will center your div element both horizontally and vertically inside the container. You can adjust the styles as needed to get the desired result. If you want to center multiple elements inside the container, you can use grid columns and rows to position them as needed.

Further Readings

CSS

How to use CSS container queries or element queries

Please share
Tags: