Margin is the space between different elements. This space is between the box of one element from box of the other element. CSS Margin Properties are used to control the distance between elements to make improve the look of the elements with respect to each other. CSS Margin is defined as AUTO, distance in pixels or distance in %age of the element for which margin is being defined.
CSS Margin properties are MARGIN, MARGIN-TOP, MARGIN-LEFT, MARGIN-RIGHT and MARGIN-BOTTOM. The allowed values for these properties are number as pixel (e.g. 10px) and number as percentage (e.g. 10%).
Using CSS Margin
While defining the Margin of an element keep these things in mind
- Since Margin values are the spaces between the borders of different elements, it cannot be negative. Always provide positive value with px or %.
- Value of margin is always with reference to the container element’s border.
- The Margin for all the four sides of the HTML element can be set using MARGIN property. If you need to set Margin for individual sides of an element you can use any of the properties from MARGIN-TOP, MARGIN-LEFT, MARGIN-RIGHT and MARGIN-BOTTOM.
- CSS MARGIN property is a composite statement to set Margin values for all sides. These values can be specified with MARGIN for the sides in the order of top, right, bottom and left sides.
- The order of values from left to right given with single statement MARGIN property will define the margin values for top, right, bottom and left sides.
- If only one value is given with MARGIN property, it is taken as Margin value for all sides.
- When you want to define margins for specific sides of the HTML element using MARGIN (composite property of all sides) then you must give value 0 for those sides.
Example CSS Margin
<HTML> <BODY style="background-color:#ff6347;"> <H4 STYLE="BORDER-STYLE:SOLID; MARGIN:10px">Using MARGIN with one value applied to all sides</H4> <H4 STYLE="BORDER-STYLE:SOLID; MARGIN:10%">Using MARGIN with one value applied to all sides</H4> <H4 STYLE="BORDER-STYLE:SOLID; MARGIN-LEFT:40px">Using MARGIN with left value</H4> <H4 STYLE="BORDER-STYLE:SOLID; MARGIN-RIGHT:20px">Using MARGIN with right value</H4> <H4 STYLE="BORDER-STYLE:SOLID; MARGIN-TOP:50px">Using MARGIN with top value</H4> <H4 STYLE="BORDER-STYLE:SOLID; MARGIN-BOTTOM:10px">Using MARGIN with bottom value</H4> <H4 STYLE="BORDER-STYLE:SOLID; MARGIN:40px 0 50px 0">Using MARGIN 0 for right and left sides</H4> <H4 STYLE="BORDER-STYLE:SOLID; MARGIN:2px 0 0 80px;">Using MARGIN 0 for right and bottom sides </H4> </BODY> </HTML>