How to center a div in 2021

Damian Wróblewski - November 2021

How to center a div in 2021

Table of contents

  1. Flexbox
  2. Grid
  3. Position
  4. Margin
  5. How to center a content?

Developers often focus mainly on javascript and forget about skilling up CSS, which can cause a lot of problems with potentially simply tasks. If you don't understand CSS fundamentals well, you will waste hours trying to fix quite simple issues. In this post we will cover one of the most memogenic CSS topic - how to center elements. There are several ways to do it.

Vertically centered meme

Flexbox

Currently the most widely used method is flexbox:

1.parent {
2 display: flex;
3 justify-content: center; // horizontal centering
4 align-items: center; // vertical centering
5}

To place element in the middle of window horizontally and vertically, parent element has to be stratched across the entire width and height of window:

1.parent {
2 width: 100vw;
3 height: 100vh;
4 display: flex;
5 justify-content: center; // horizontal centering
6 align-items: center; // vertical centering
7}

OR

1.parent {
2 width: 100vw;
3 height: 100vh;
4 display: flex;
5}
6
7.child {
8 margin: auto;
9}

Grid

To center elements you can use CSS grid too:

1.parent {
2 display: grid;
3 place-content: center; // horizontal and vertical centering
4}

OR

1.parent {
2 display: grid;
3}
4
5.child {
6 margin: auto;
7}

Position

A slightly older method is centering using the position property:

1.parent {
2 position: relative;
3}
4
5.child {
6 position: absolute;
7 top: 50%;
8 left: 50%;
9 transform: translate(-50%, -50%);
10}

In this case keep in mind that elements with position: absolute go out of document's flow and it may cause problems with positioning other nearby elements.

Margin

Because of the way the height of elements is calculated, with the margin property we can only center elements horizontally. Keep in mind that positioned element must have a specified width.

1.parent {
2 width: 100vw;
3}
4
5.child {
6 width: 100px;
7 margin: 0 auto;
8}

How to center a content?

To center a content inside a block element (e.g. text in a div) you can use text-align and vertical-align:

1.parent {
2 text-align: center; // horizontal centering
3 vertical-align: middle; // vertical centering
4}

If you find inaccuracy in this post or you know another interesting way to solve this problem, contact me via social media or contact form 😉


Join the discussion