CSS Margin
The CSS margin property controls the space around an element. It is transparent and has no background color, creating an empty area around the element.
You can adjust the margins for the top, bottom, left, and right individually with separate properties. Alternatively, you can use the shorthand margin property to modify all four margins at once.
The following are the CSS margin properties:
CSS Margin Properties
CSS Margin Values
Here are some possible values for the margin property:
CSS Margin Example
You can set different margins for each side of an element.
<!DOCTYPE html>
<html>
<head>
<style>
p {
background-color: orange;
}
p.para {
margin: 50px 101px;
}
</style>
</head>
<body>
<p>This paragraph does not have a specified margin.</p>
<p class="para">This paragraph has a specified margin.</p>
</body>
</html>
Output
Margin:Shorthand Properties
The CSS shorthand property is used to simplify the code by defining all margin values in a single property.
There are four ways to set the margin property. You can use any of the following:
- margin: 50px 100px 150px 200px;
- margin: 50px 100px 150px;
- margin: 50px 100px;
- margin: 50px;
Margin: 50px 100px 150px 200px;
It means that:
- The top margin is 50px
- The right margin is 100px
- The bottom margin is 150px
- The left margin is 200px
Example
<!DOCTYPE html>
<html>
<head>
<style>
p {
background-color:orange;
}
p.para {
margin: 50px 100px 150px 200px;
}
</style>
</head>
<body>
<p>This paragraph does not have a specified margin.</p>
<p class="para">This paragraph has a specified margin.</p>
</body>
</html>
Output
Margin: 50px 100px 150px;
It means that:
- The top margin is 50px
- The left and right margins are 100px
- The bottom margin is 150px
Example
<!DOCTYPE html>
<html>
<head>
<style>
p {
background-color: orange;
}
p.para {
margin: 50px 100px 150px;
}
</style>
</head>
<body>
<p>This paragraph does not have a specified margin.</p>
<p class="para">This paragraph has a specified margin.</p>
</body>
</html>
Output
Margin: 50px 100px;
It means that:
- The top and bottom margins are 50px
- The left and right margins are 100px
Example
<!DOCTYPE html>
<html>
<head>
<style>
p {
background-color: orange;
}
p.para {
margin: 50px 100px;
}
</style>
</head>
<body>
<p>This paragraph does not have a specified margin.</p>
<p class="para">This paragraph has a specified margin.</p>
</body>
</html>
Output
Margin: 50px;
It means that:
- The top, right, bottom, and left margins are all 50px.
Example
<!DOCTYPE html>
<html>
<head>
<style>
p {
background-color: orange;
}
p.para {
margin: 50px;
}
</style>
</head>
<body>
<p>This paragraph does not have a specified margin.</p>
<p class="para">This paragraph has a specified margin.</p>
</body>
</html>