About me

I am a full stack .net developer with 5 years of experience in front-end and back-end technologies like HTML, CSS, Jquery, Angular, Typescript, Bootstrap, C#, MSSQL and Mongodb. I have done Btech Computer engineering from Sigma Institute of Engineering & Technology that comes under GTU (Gujarat Technological University). I have worked on web applications, Web APIs, Windows Forms, Web Forms, Tray applications and corporate websites. Programming is my hobby and I have starting writing blog to provide a platform for those who want to grow their careers as a fullstack .NET developers.

Aligning HTML Element to the Center

This article is about ways to center align any HTML element to the center of its parent element. In this article, we will align a square to the center of a division as shown in the below image:

Example 

HTML:

<div class="border">
<div class="square"></div>
</div>

CSS:

.square {
  width: 100px;
  height: 100px;
  background: blue;
}
.border {
  border: 1px solid #000;
  width: 500px;
  padding: 10px;
}

Way 1: Setting CSS properties, text-align: center for the parent element and margin: 0 auto for the inner element

In our example, the division with the class border is the parent element and the one having class square is the inner element. So, we will add the below CSS:

.square {
  margin: 0 auto;
}
.border {
  text-align: center;
}

Way 2: Setting CSS properties, text-align: center for the parent element and display: inline-block for the inner element

.square {
  display: inline-block;
}
.border {
  text-align: center;
}

Way 3: Setting CSS properties, display: table-cell for the parent element and margin: 0 auto for the inner element

.square {
  margin: 0 auto;
}
.border {
  display: table-cell;
}

Jsfiddle link: Example: Aligning HTML element to the center

I hope this article is useful for those who struggle aligning HTML elements to the center. For any queries, you can write to me at [email protected]. To get notified for the releases, subscribe through email. If you found this article useful, please share it. Thank you 😊.