CSS — Margin & Padding
Margin
Margins are actually the same as the relative positioning. The only difference between them is that margin adds defined space to all sides of the element.
Get TARUN KUMAR’s stories in your inbox
Join Medium for free to get updates from this writer.
Margins are used to position the element while keeping them in the flow of the page but positioning is used to position elements when you want to take your element out of the flow of the page.
margin: 100px;To add different margins to side use:
margin: 200px 100px;Here, top and bottom margin will be 200px & right and left margins will be 100px.
To add totally different margins to all sides of element use:
margin: 100px 200px 50px 300px;Here, the pixels defined are applied to element in clockwise direction i.e., 100px margin on top, 200px margin on right, 50px margin on bottom and 300px margin on left.
Another thing that if you want to add a margin on a specific side of the element then you can use the following:
margin-top: 10px;
margin-right: 10px;
margin-bottom: 10px;
margin-left: 10px;Setting the margin to “auto” will position the element in the center of the parent element.
Padding
Padding is very similar to margin. It allows us to do the same thing but inside the element.
padding: 100px;You can see that the div is expanded by 100px to all sides. It actually added 100px space to all sides of the elements but from inside. Now because it is similar to margin, the properties will be applied the same way. To add different padding on sides:
padding: 10px 20px,To add different padding to all sides:
padding: 10px 15px 5px 20px;To add padding on a specific side of an element:
padding-top: 10px;
padding-right: 10px;
padding-bottom: 10px;
padding-left: 10px;You can see that there is some white space between the divs and also at the sides of the webpage.
It actually comes with the default value from the web browser. To remove that use:
body {
margin: 0;
padding: 0;
}
h1 {
margin: 0;
padding: 0;
}Now every browser has different styling and if you want your website to look the same in all web browsers then you might want to dive deep into “CSS reset”. Google it and do some research about it.
Instructor ~ TARUN KUMAR










