How to center elements in CSS in 2022

Wahey it's the future now and centering stuff with CSS is easy peasy.

Three methods below. Depending on your situation one of these should do the trick.

Method 1 - Grid

Centering stuff using CSS Grid is super simple. As long as you can set the parent element to be display: grid you can add the place-content property and set it to center and you should be good to go.

<div class="parent">
  <p>sup</p>
</div>
.parent {
  display: grid;
  place-content: center;
}

Method 2 - Flex

Centering using flexbox requires an extra parent element, this is obviously not ideal. But if you need to, you can do this:

<div class="boo">
  <div class="parent">
    <p>sup</p>
  </div>
</div>
.boo {
  display: flex;
  justify-content: center;
}
.parent {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

Basically what we're doing here is creating one flex context (.boo), and that'll have the default flex-direction of row, meaning it's a horizontal flex context, then justify-content: center to center the content within. Then inside that we have another flex context (.parent), this time vertical. Again justify-content: center to center the content. So we're centering both horizontally and vertically with separate flex contexts, hence the requirement of an extra parent element. (booooo).

You might find yourself stuck with this method if the circumstances are right, for example if you're already working with flex containers or if you're writing CSS for a React Native app.

Method 3 - Transforms

The classic.

<div class="parent">
  <p class="child">sup</p>
</div>
.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Set the parent element to relative, this will give the child element the correct positioning context for it's absolute position. Then set the child element to be top and left 50%, this will position the element roughly in the center, except it'll be the top left corner of the element which is actually centered, to fix this move the element left and up by 50% of it's own proportions with transform: translate(-50%, -50%).