Tip #1 : Centering elements without flexbox and automatic margins

Subscribe to my newsletter and never miss my upcoming articles

This neat little trick allows you to center elements anyway you want in almost any situation. I found this trick when I was trying to vertically center a relative element in its container. I found out that you can use this trick to also horizontally center elements. Useful when margin: 0 auto; or flexbox doesn't work. Anyway here's the code :

Note only use this method as a last resort, if you can use to automatic margins or flexbox, use those methods instead

I initially found this trick here

The code bit by bit :

Horizontal centering

.container {
  position: relative;
}

.center__horizontal {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

Vertical centering

.container {
  position: relative;
}

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

Vertical & Horizontal centering

.container {
  position: relative;
}

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

Center a relative Element to its container

.container {
  width: 550px;
  height: 150px;
  background: #eaeaea;
}

.center__relative {
  position: relative;
  width: 50px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

No Comments Yet