CSS

Center a Div

So, a famous question: “How to center a div?“.
There are many ways to center a div. I’ll show you 4 (modern ways) to center a div horizontally and vertically, including my favorite – via flexbox.

Let’s start!

1. Using flex, align-items and justify-content

So, in this example, I’m using flex to center a div. This is my favorite. I prefer flex over grid wherever it makes sense because it’s more beginner-friendly.
Important notice: I’m applying the styles on parent div!

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

Demo:

HTML CSS Preview
.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}

2. Using grid and place-items

In this example, I’m using grid to center a div.
Important notice: I’m again applying the styles on parent div!

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

Demo:

HTML CSS Preview
.parent {
  display: grid;
  place-items: center;
}

3. Using flex and margin

I’m using flex and margin to center a div in this example. This time I’ll apply the flex property to the parent element and margin: auto to the child element.

Let’s take a look:

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

Here's the demo:

HTML CSS Preview
.parent {
  display: flex;
}
.child {
  margin: auto;
}

4. Using grid and margin

This example is the same as the previous one. Only this time I use grid instead of flex.
Let’s center that div!

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

And, here is the final demo of centering a div. No more memes:

HTML CSS Preview
.parent {
  display: grid;
}
.child {
  margin: auto;
}
Did you like this CSS code snippet? Share it with your friends: