Four Simple Ways To Center a Div With CSS

Ishan Rijal
3 min readJan 31, 2022
Center Div

To clearly understand this, let’s create two div elements. One div element as a ‘parent’ and the other as a ‘child’. Create the HTML and CSS file as below.

Step 1

1. Flex

To do using flex property add display: flex; property to the parent class.

i. If you want to align items horizontally i.e. in the x-axis, use another property justify-content: center;

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

ii. If you want to align items horizontally i.e. in Y-axis, use another property align-items: center;

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

iii. If you want to align items horizontally i.e. in Y-axis and vertically i.e. in X-axis both then, use both property justify-content: center; align-items: center;

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

2. Text-align

To do using the text-align property write code as shown in step 1 image as in code pen. Add text-align: center to the parent element. Adding only this won’t center the div. We need to add display:inline-block property to the children element to center the div. This will center the div horizontally.

.parent-element{text-align:center; }

.child-element{display: inline-block;}

3. Margin

To do using the margin property write code as shown in step 1 image as in code pen. Add margin: 0 auto; to the children element. It centers the div horizontally.

.child-element{margin: 0 auto;}

4. Position

To do using the margin property write code as shown in step 1 image as in code pen. Add position: relative; to the parent element.

.parent-element{position:relative;}

Then add position: absolute, left, right, and translate property to the children element.

The translate()CSS Function repositions an element in the horizontal and/or vertical directions. To know more about translate() visit here.

Source: MDN Web Doc

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

This will center the div both horizontally and vertically.

I think the above steps are clear and simple. Following the above step, you can clearly center the div.

--

--

Ishan Rijal

Hey, I am high school graduated computer science student.