How to vertically align stuff using CSS

Here is the best ways to vertically align DOM elements using CSS.

Using transform

Probably the most reliable way of doing it, because the element will always stay centered no matter what (and without deforming).

.container {
  position: relative;
}
.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Using flexbox

Easier to use, but the centered element might get squished if the container becomes smaller than it's content.

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

Using negative margins

My old way of doing it back when CSS3 didn't exist.

Restrictions : the element has to be squared (because for some reasons, a percentage value in margin-top will be relative to container width instead of container height).

And we have to add an extra div around centered element.

.container {
  position: relative;
}
.pre-centered {
  position: absolute;
  top: 50%;
  left: 50%;
}
.centered {
  margin-top: -50%;
  margin-left: -50%;
}