In sometime, we want to center one div in our layout, but css doesn‘t provide one property for this.
we should use margin properties to implement.
First let we see the standard explanation about Margin in W3Schools.
Margin
The margin clears an area around an element (outside the border). The margin does not have a background color, and is completely transparent.
The top, right, bottom, and left margin can be changed independently using separate properties. A shorthand margin property can also be used, to change all margins at once.
Possible Values
Value | Description |
---|---|
auto | The browser calculates a margin |
length | Specifies a margin in px, pt, cm, etc. Default value is 0px |
% | Specifies a margin in percent of the width of the containing element |
inherit | Specifies that the margin should be inherited from the parent element |
Center one div will use margin auto property.
With W3school explanation, we still don‘t understand the exact mean of auto; let‘s have a look at below screenshot for explanation.
we have two divs named as ‘content‘ and ‘centerContent‘.
for ‘content‘ div, it width is 500px;
for ‘centerContent‘ div, it width is 300px;
if we setup ‘centerContent‘ div margin property as
margin:0 auto;
it means
margin-top:0;
margin-right:auto;
margin-bottom:0;
margin-left:auto;
Css will calculation the margin-right and margin-left by this rule:
(‘content‘ div width - ‘centerContent‘ div width)/2 = (500-300)/2 = 100px; the real margin by calculation is:
margin-top:0;
margin-right:100px;
margin-bottom:0;
margin-left:100px;
in this way, it will center ‘centerContent‘ div as we expected.
if we also want to the text in this div also is also in center, we should add one additional property like this
text-align:center;
in one word, three properties should setup for this div:
width,margin and text-align.