CSS Centering is not hard

Made by Marvin Drude

CSS Centering is not hard

Many people think centering content in CSS is difficult, so I thought I am going to put together a list of useful tips.

Vertical

I must admit that centering vertically is harder than it should be.

Inline-elements

Just apply same padding in order to have it appear vertically centered.

.nav-link {
  padding: 10px 0px;
}

Block-elements

This works for every block element, even if you don’t know exact values.

.super {
  position: relative;
}

.sub {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

Horizontal

Inline-elements

This is very simple and useful. Just apply this to the parent of the child/children you want to center.

.center {
  text-align: center;
}

Block-elements

You have to set a specific width to the element and just have to set the margin left and right to auto.

.center {
  margin: 0 auto;
}

This causes one element to be centered horizontally and multiple elements will be below each other. If you want them to be along side each other, you could try inline-block.

.parent {
  text-align: center;
}

.child {
  display: inline-block;
}

Both

This is straight forward.

.parent {
  position: relative;
}

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