Centering in CSS - Horizontally, Vertically

Centering Things in CSS is a bit hard. The problem is which way to reach for among the different ways available to Center Elements in CSS. In this tutorial, I have explained how to center an element with CSS Vertically, Horizontally, at Block Levels.

How to center horizontally?

Centering elements horizontally is quite simple compared to vertical centering. We have present different ways to center the elements horizontally. To change the text to center horizontally is quite simple. You can simply set the text-align property to center in order to center an element horizontally.

p { 
  text-align: center; 
}

How to center horizontally with flexbox?

The modern way to center anything is to use Flexbox rather than going with the text.

#mysection { 
  display: flex; 
  justify-content: center; 
}

Any element within my section will be centered horizontally by using the above code. There is an alternative method to go with if you don't want to use the flexbox.

How to center horizontally using CSS margin auto?

Anything which is not text can be centered by applying an automatic margin on the left and right and set the width of the element.

section { 
  margin: 0 auto; 
  width: 50%; 
}

The above margin: 0 auto; is a shorthand for

section { 
  margin-top: 0; 
  margin-bottom: 0; 
  margin-left: auto; 
  margin-right: auto; 
}

Do remember to set the item to display: block if it is an inline element.

How to Center Vertically using Flexbox?

Centering an element vertically can be a difficult task. Flexbox gives us a simple way to center alignment vertically.

#mysection { 
  display: flex; 
  align-items: center; 
}

Any element within my section will be centered vertically.

How to Center Both Vertically and Horizontally using Flexbox?

You can combine the flexbox techniques to center both vertically and horizontally for an element in the page.

#mysection { 
  display: flex; 
  align-items: center; 
  justify-content: center; 
}

How to Center Vertically and Horizontally using CSS Grid?

We can perform the same using CSS Grid:

body { 
  display: grid; 
  place-items: center; 
  height: 100vh; 
}

17