5 ways to center a div using CSS


how to center div

How we can center a div horizontally and vertically. In this blog, I show you five different ways to achieve that. First of all, we will take a div called 'parent,' and inside that, we will take another div named 'child.' our objective is to center the 'child' div to the 'parent' div. The HTML code looks like follows.

html code

1. First Method ( Using CSS3 Flexbox )

Flexbox is a CSS3 Web layout model, and its responsive elements are arranged automatically within a screen size. Box layout of flexbox helps center a div without floating and positioning the 'child' div in respect to the 'parent' div. The following CSS applying to the 'parent' div will automatically center the 'center' div horizontally or vertically.

image 2

2. Second Method ( using Tables )

The second method is to apply the table method. The following CSS will center the child div compare to the parent div.

3. Third Method ( CSS Grid )

The next method is the CSS grid method. Using a grid-based layout system, we can center the 'child' div horizontally and vertically without using float and positioning it.

css grid

4. Fourth Method ( margin Auto )

The next method is to apply margin auto-style on a display flex item. In this way, we have to apply display: flex to the parent div and then apply margin: auto to the child div. the CSS will be as follows:

css margin auto

5. Fifth Method ( Using Position )

In this method, we will apply position relative to the parent div. Then we will provide absolute position value to child div. We will then apply top and left values of 50% and finally apply CSS transform and translate value to make it to the center for centering the div.

css position property

I hope you liked this. If you find this useful, then Please share the articles of this blog and follow us on our social media profiles. Thanks for visiting the blog. 

Please do not enter any spam link in the comment box.

Post a comment

Please do not enter any spam link in the comment box.

Post a Comment (0)

Previous Post Next Post