In web design, margins play a crucial role in defining the spacing around an element. Here, we’ll learn about the essential concepts of CSS margins. Understanding these properties is crucial for creating well-designed web layouts. We’ll cover their definitions, usage, best practices, and examples.
What are Margins?
The CSS margin property allows us to create space around an element. They define the gap between an element and its neighboring elements. Margins can be set individually for each side (top, right, bottom, left).
Margin Values
- Length (e.g.,
px
, rem, em, ex, vh, vw, etc
)
- Percentage (relative to the element’s width)
auto
 (calculated by the browser)
- margin allows negative values.
Margin Properties
margin-top
: Sets the top margin of an element.
margin-right
: Sets the right margin of an element.
margin-bottom
: Specifies the margin at the bottom of an element.
margin-left
: Determines the width of the margin on the left side of an element.
Syntax:
body {
margin: value;
}
Example of margin property with 4 values:Â
margin: 40px 100px 120px 80px;
- top margin = 40px
- right margin = 100px
- bottom margin = 120px
- left margin = 80px
Example:Â This example describes the margin property by specifying the four values.
HTML
<!DOCTYPE html>
< html >
< head >
< style >
p {
margin: 80px 100px 50px 80px;
}
</ style >
</ head >
< body >
< h1 >
GeeksforGeeks
</ h1 >
< p > Margin properties </ p >
</ body >
</ html >
|
Output:
Example of margin property with 3 values:Â
margin: 40px 100px 120px;Â
- top = 40px
- right and left = 100px
- bottom = 120px
Example:Â This example describes the margin property by specifying the three values.
HTML
<!DOCTYPE html>
< html >
< head >
< style >
p {
margin: 80px 50px 100px;
}
</ style >
</ head >
< body >
< h1 >
GeeksforGeeks
</ h1 >
< p >
Margin properties
</ p >
</ body >
</ html >
|
Output:
Example of margin property with 2 values:
margin: 40px 100px;Â
- top and bottom = 40px;
- left and right = 100px;
Example:Â This example describes the margin property by specifying the double value.
HTML
<!DOCTYPE html>
< html >
< head >
< style >
p {
margin: 100px 150px;
}
</ style >
</ head >
< body >
< h1 >
GeeksforGeeks
</ h1 >
< p >
Margin properties
</ p >
</ body >
</ html >
|
Output:
Example of margin property with 1 value:Â
margin: 40px;Â
- top, right, bottom and left = 40px
Example: This example describes the margin property by specifying the single value.
HTML
<!DOCTYPE html>
< html >
< head >
< style >
p {
margin: 100px 150px;
}
</ style >
</ head >
< body >
< h1 >
GeeksforGeeks
</ h1 >
< p >
Margin properties
</ p >
</ body >
</ html >
|
Output:
Supported Browser
- Google
- Microsoft Edge
- Firefox
- Opera
- Safari
Last Updated :
07 Mar, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...