Every developer must have come across the task of centering the div horizontally or vertically. While experienced developers have their handy techniques but for beginners, it is often complicated and tricky. So in this article, we will share 6 different and easy ways to center a div horizontally and vertically in CSS.
So basically, we have two div’s, one parent and one child. We need to center the child div concerning parent div. For this, let’s see 6 different methods.
1. Method 1: Using Grid
Using a grid, we have two ways to achieve our target first is by using place-items, and the second is by using align-self and justify-self.
i. With place-items, for centering the child item, we set the rules for the parent element. We set the parent display: grid and place-items: center, and there you go, your work is done.
ii. In a second way, we set the parent display: grid and assign the properties, i.e., align-self: center(for vertically centering the div) and justify-self: center(for horizontally centering the div) to the child element.
Note: These properties are solely for the CSS grid.
2. Method 2: Using Flex
In the second method, all rules are defined for the parent element. We set the parent display: flex and the main properties, i.e., justify-content: center(for horizontal alignment) and align-items: center(for vertical alignment).
3. Method 3: Using Position and CSS transform
It is one of the most used methods by developers. In this method, we make the child element position: absolute to the parent element and give the child container the position of 50% from the top and 50% from the left.
4. Method 4: Using Position
It is the most basic and easy method for centering the div. Same as method 3, we make the child element position: absolute to the parent element and then set the child container the left, right, top, and bottom properties to 0 along with the margin set to auto.
5. Method 5: Using CSS Margin
We can also center a div solely with the help of margin property. In this method, all we need to do is set margin: 0 auto. It is one of the ancient methods which works well on all browsers.
6. Method 6: Using CSS Tables
I know after reading this, you must be surprised, but yes, we can center our content and elements in the container using CSS tables.
We have to set the display: table to the wrapper ,i.e., level above the parent and then display: table-cell property in the parent.
And now we can do it in two ways in the child element:
- First, by using the margin property, i.e., setting the margin: 0 auto
- Second, by using the display: inline-block
So that’s all. I hope you find all the ways easy and helpful. Now give a try at each of the methods and find one which suits you the best. Also, if you have any questions or suggestions, let us know by writing in the comment section below.