Easy ways of centering elements in css

Easy ways of centering elements in css

Centering anything in css sometimes could be very difficult at times, here are some easy and simple ways for you to center your items.

There are many ways of doing this but the conventional approach is making the parent position relative and the child you want to center to position absolute, and then set the top and left properties to 50% then use the transform property to translate it by (-50%,-50%).

.parent { 
  position: relative;
}

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

another approach of doing this is by using flexbox when we set the parent element to display: flex and then align-items: center and justify-content: center. and there you have it.

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

But don't worry there's an easier way of doing this, and it's by using the grid layout.

just make the parent element display as a grid and place-items: center , there you go, you have centered it both horizontally and vertically, easy right?

.parent { 
  display: grid;
  place-items: center;
}

Other Articles