In a web page, use the Margin property to give space outside the element and to give space between two elements. An element is given margin from top, right, bottom, and left. Its value is px, In cm, em, etc, you can give the property of margin as follows -
1 margin
2 margin-left
3 margin-right
4 margin-top
5 margin-bottom
Giving a value to this property applies margin space to the top, right, bottom, and all of these together, giving 4 values to each of these properties separately, giving these values respectively top, Applies to Right, Bottom, and Left, can give its value in px, auto cm, em, etc.
Example: 1
<!DOCTYPE html> <html> <head><title></title></head> <body> <p style="margin: 35px;"> paragraph 1</p> <hr> </body> </html> |
Output
Giving the value auto to the margin is displayed horizontally at the center of the text web page, by using this value, equal margin space is displayed in the left and right.
Example 2
<!DOCTYPE html> <html> <head> <style> p { width:300px; margin: auto; border: 1px solid red; } </style> </head> <body> <p> margin auto example </p> </body> </html> |
Output
The element displayed in the web page uses it to give top to margin space, its value is given in px, cm, em, etc.
The element displayed in the web page uses it to give right to margin space, its value is given in px, cm, em, etc.
The element displayed in the web page uses it to give margin space from the bottom, its value is given in px, cm, em, etc.
The element displayed in the web page uses it to give left to margin space, its value is given in px, cm, em, etc.
Example 3
<!DOCTYPE html> <html> <head><title></title></head> <body> <p style=" margin-top: 20px; margin-right: 30px; margin-bottom: 65px; margin-left: 70px;">This is a paragraph</p> <hr> </body> </html> |
Apart from these, you can use shorthand properties to give margin.
When 4 value is given in a property, it is applied in top, right, bottom, and left respectively.
1 If 3 value is given then the value given to right will also apply to left.
2 If 2 value is given, the value given for top will be applied at the bottom and the value given for right will also be applied to the left.
3 If 1 value is given, top, right, bottom, left will all apply the same value.
This is called shorthand property
Example 4
<!DOCTYPE html> <html> <head><title></title></head> <body> <p style="margin: 20px 30px;">This is a paragraph</p> <hr> </body> </html> |