Alwar G
Posted on March 25, 2020
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;
}
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.
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
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.
Posted on March 25, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.