# How to Center an Element with CSS? | 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, we 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.

Also, See:

## 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;
}
Categories CSS