How does auto property work in margin:0 auto in CSS ?
In this article, we will learn how auto property works in margin:0 auto in CSS. The margin property is used to set the margins for an element. The margin property has four values margin-top, margin-right, margin-bottom, and margin-left.
Syntax:
margin: top_margin right_margin bottom_margin left_margin; /* We can also use the shortened syntax of margin that takes only two parameters */ margin: top_and_bottom_margin left_and_right_margin;
So in margin: 0 auto, the top/bottom margin is 0, and the left/right margin is auto, Where auto means that the left and right margin are automatically set by the browser based on the container, to make element centered. The margin: 0 auto equivalent to:
margin-top:0; margin-bottom:0; margin-left:auto; margin-right:auto;
Example:
HTML
<!DOCTYPE html> < html lang = "en" > < head > < style > .parent{ background-color: yellow; /* It set top and bottom margin to 5% and, the left and right are automatically set by browser */ margin: 5% auto; } .h1{ color: rgb(5, 138, 5); font-size: 50px; } </ style > </ head > < body > < div class = "parent" > < h1 class = "h1" >GeeksforGeeks</ h1 > </ div > </ body > </ html > |
Output:
Before set margin:
After set margin:
Please Login to comment...