5 Ways To Center a Div In CSS

5 Ways To Center a Div In CSS

Center a div easily with these five methods

"How to center a div".

This is probably the most googled programming question. It is a problem that frequently affects both new and experienced developers. Let's look at five different ways to center a div in CSS.

  • With grid property

We can center a div using the grid property by simply setting the display to grid and the place-item property to center.

Example

.grid-demo {
        display: grid;
        place-items: center;
}
  • With flexbox property

Another way to center a div is by using the flexbox property. Setting the display to flex, align-items to center, and justify-content to center will achieve the desired results.

Example

.flexbox-demo {
        display: flex;
        align-items: center;
        justify-content: center;
}
  • With position property

We can as well center a div using the position property together with the top, left, and transform properties.

Example

.position-demo {
        position:  absolute;
        top:  50%;
        left:  50%;
        transform:  translate(-50%, -50%);
}
  • With both flex and margin properties

We can combine the flex and margin properties to center a div in two ways. We must first of all create a parent element in which the display will be set to flex and then create a child element and set the margin to auto.

Example

.parent {
        display:  flex;
     }
.child {
        margin: auto;
   }
  • With both grid and margin properties

Similar to flex and margin. We can achieve this by also creating a parent element with the display grid and a child element with the margin auto.

Example

.parent  {
           display:  grid;
    }
.child  {
           margin:  auto;
  }

Know of any other ways to center a div? Let's hear about it in the comments!