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 margins are automatically set by the browser based on the container, to make the element centered. The margin: 0 auto equivalent to:
margin-top:0;
margin-bottom:0;
margin-left:auto;
margin-right:auto;
Example: In this example, we are using an above-explained approach
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 setting the margin:

After set margin:

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
08 May, 2023
Like Article
Save Article