The margin is the space outside the HTML element. It gives external spacing and differentiates two or more elements. Consider the image:
Here, the space outside the border is the margin.
Syntex
<style>
selector {
margin: value;
}
</style>
The margin value can be used in any of the following methods:
Method 1
<style>
selector {
margin: value;
}
</style>
Here, the margin value will apply an equal margin to all sides (top, right, left, and bottom).
Example:
<html lang="en">
<head>
<style>
#p1{
border:2px solid #23Dafa;
}
#p2{
margin:12px;
border:2px solid #f23;
}
</style>
</head>
<body>
<p id="p1">CodeWithRahul (Without Margin)</p>
<p id="p2">CodeWithRahul (With Margin)</p>
</body>
</style>
Output
Note:-Values can be specified in different units, such as pixels (px), em, rem, percentage (%), auto, etc. If you are not familiar with borders, you can also check out the CSS borders tutorial.
Method 2
<style>
selector {
margin: value value;
}
</style>
Here, value 1 is the vertical margin (y-axis), and value 2 is the horizontal margin (x-axis).
Example:
<html lang="en">
<head>
<style>
#p1{
border:2px solid #23Dafa;
}
#p2{
margin:20px 50px;
border:2px solid #f23
}
</style>
</head>
<body>
<p id="p1">CodeWithRahul (Without Margin)</p>
<p id="p2">CodeWithRahul (With Margin)</p>
</body>
</style>
Output
Note: You can use the inspect tool to verify.
Method 3
<style>
selector {
padding: value1 value2 value3 value4;
}
</style>
In this method, each value represents the margin of individual sides (top, right, bottom, left).
Example:
<html lang="en">
<head>
<style>
#p1{
border:2px solid #23Dafa;
}
#p2{
margin:15px 30px 25px 50px;
border:2px solid #f23
}
</style>
</head>
<body>
<p id="p1">CodeWithRahul (Without Margin)</p>
<p id="p2">Code With Rahul (With Margin)</p>
</body>
</style>
Output
In this example, the marginon individual sides is
Playaround:
1. You can also check the Margin of each HTML element(s) using the inspect tool. Follow the steps.