Centering Elements in CSS

Centering in CSS: A Complete Guide Centering in CSS is hard for beginners learning frontend development which even I faced So here I am with my blog which shows how to center elements in CSS

·
15th February, 2023
views

To Center Elements Horizontally

Center an Inline element.

To center inline elements we can use text-align

.box{
   text-align:center;
}

Center a block level element

By default block level elements take 100% width. To center block level elements we can set its margin-left and margin-right to zero.

.box{
   margin:0 auto;
}

Centering Elements Vertically

Center an Inline element vertically

We can use equal padding above and below the inline element

.box{
   padding-top:20px;
   padding-bottom:20px;
} 

Center a Block element vertically

Method 1 using FlexBox

We need to set parent element's display as flex and justify-content to center flex-direction by default is set to row so we need to modify it to column.

.parent {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

Center Block elements vertically. Alternative method

Set parent's position as relative and that of child element as absolute.

Child element is pushed off from parent's top by 50%, using top and brought up by 50% of the height of the child element using transform.

.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

Centering elements Horizontally & Vertically

We can combine above techinques

Using flex box we can implement this. Setting parent elements display to flex and justify-content and align-items to center.

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

Alternative method

We can center elements vertically and horizontally using grid too.

body, html {
  height: 100%;
  display: grid;
}
span { 
  margin: auto;
}

Centering elements using position:absolute (Method 3)

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

I hope you learnt something!

Happy Coding!!

Built with TypeScript, Tailwind and Next.js