CSS margin Property
CSS margin property sets the margin for the HTML element on all the four sides.
margin is a short hand property to specify margin-top, margin-right, margin-bottom, and margin-left properties in a single shot.
margin property can be assigned with one, two, three, or four values.
margin: 35px 25px 45px 65px;
margin: 35px 25px 45px;
margin: 35px 25px;
margin: 35px;
We shall go through each of these scenarios with examples.
margin with four values
An example for margin property set with four values.
margin: 35px 25px 45px 65px;
where the order of sides is top, right, bottom, and left respectively, as shown in the following.
margin: 35px 25px 45px 65px;
/* top right bottom left */
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
#p1 {
border: 1px solid #DDD;
margin: 35px 25px 45px 65px;
}
</style>
</head>
<body>
<p id="p1">Hello World</p>
</body>
</html>
The computed values for the HTML Element in the browser’s developer console would be shown as in the following. Observe the margin section marked in brown color.
margin with three values
An example for margin property set with three values.
margin: 35px 25px 45px;
where the order of sides is top, right, and bottom respectively. For left, the value for right is considered, as shown in the following.
margin: 35px 25px 45px;
/* top right bottom */
/* left */
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
#p1 {
border: 1px solid #DDD;
margin: 35px 25px 45px;
}
</style>
</head>
<body>
<p id="p1">Hello World</p>
</body>
</html>
margin with two values
An example for margin property set with two values.
margin: 35px 25px;
where the first value is for top and bottom side margin, and the second value is for right and left side margin, as shown in the following example.
margin: 35px 25px;
/* top right */
/* bottom left */
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
#p1 {
border: 1px solid #DDD;
margin: 35px 25px;
}
</style>
</head>
<body>
<p id="p1">Hello World</p>
</body>
</html>
margin with one value
An example for margin property set with only one value.
margin: 35px;
where the specified value is set as margin for all sides: top, right, bottom, and left, as shown in the following.
margin : 35px;
/* top */
/* right */
/* bottom */
/* left */
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
#p1 {
border: 1px solid #DDD;
margin: 35px;
}
</style>
</head>
<body>
<p id="p1">Hello World</p>
</body>
</html>
Conclusion
In this CSS Tutorial, we learned about margin property, and how to use this property for HTML Elements, with examples.