There are many ways you can center a HTML element by CSS but here I am going to describ 5 easy and quickest ways to center HTML element by CSS. In the below HTML code we will use to make center by using all CSS methods.

Sample of HTML code:


<main class="parent">
    <p class="child">
        I'm Awesome
    </p>
</main>


So let's begin...

1) Using FLex Property

The first method I am going to talk about using flex property. It is really very helpful to make a flexible responsive layout structure without using float or positioning.

CSS code


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

2) Using CSS grid

The CSS Grid is best to make a grid-based layout system, with rows and columns. It is best for making a multi-column layout website. Applying the following CSS properties to the parent class of the main element will center the child class of p element horizontally and vertically.

CSS code


.parent {
  display: grid; 
  justify-content: center; /*horizontal*/ 
  align-content: center; /*vertical*/
 }
 

3) Using Position Property

The CSS position property defines the types of positioning methods used for HTML elements. The position property has five values for positioning elements such as static, relative, fixed, absolute, sticky. In the below code, we used relative value for the parent element and absolute value for the child element.

CSS code for the parent element


.parent {
  position: relative; 
}

CSS code for child element


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

4) Using Tables

Before the flex&grid layout system appeared, Tables were the only real way to structure HTML,namely the syntax.

CSS code for the parent element


.parent {
  display: table-cell; 
  text-align: center; /*horizontal*/
  vertical-align: middle; /*vertical*/
}

CSS code for child element


.child {
  display: inline-block;
}

5) Using Margin auto with flex or grid 

We can use flex or grid value in display property for parent element and margin property value 0 auto for child element to make element horizontally and vertically center. Usually margin:0 auto makes specific elements horizontally center.

Sample of the CSS code


.parent {
  display: flex;
}
.child {
  margin:auto;
}
Thanks for reading!