DEV Community

Alwar G
Alwar G

Posted on • Updated on

How margin: 0 auto; centers the element?

Hi Everyone,

This is my first post in dev.to ​​ 😀
Here, we are going to talk about how margin: 0 auto; works

let's consider the div(.inner-div) element inside another div(.outer-div) element

HTML:
<div class="outer-div">
<div class="inner-div"></div>
</div>

CSS:
.outer-div {
width: 100px;
height: 100px;
background-color: red;
}

.inner-div {
width: 50px;
height: 100px;
background-color: blue;
margin: 0 auto;
}

Output:
Div-images

Actually the inner-div has an auto value for both margin-left and margin-right properties.

These auto values align the inner-div in the center position of outer-div.
Because the inner-div exactly has a 25px on margin-left and 25px on margin-right.

inner-div-box

Why 25px? 🤔
The outer div has a 100px width. The Inner-div has a 50px width;
Remaining width(total margin values of left and right) = 100 - 50 = 50px;

marginLeft = marginRight = 50/2 = 25px;
So, We conclude the formula as 😜

Total margin values of left and right = parent element width - child 
                                        element width
  marinLeft = marginRight = Total margin values of left and right/2
Enter fullscreen mode Exit fullscreen mode

Therefore, .inner-div is centered.

Note: margin: 10px auto: also centers the element, but it will take 10px on top as well as the bottom. So, the left and right auto values will
make the center position.

Top comments (1)

Collapse
 
theaswathprabhu profile image
Aswathprabhu R

Insightful 😁 Looking for more like this 👍🏻