Appling Margin to an Element

Margin is space between the element border and surroundings.

The margin properties are:

PropertyDescriptionValues
margin-toptop margin auto or <length> or <%>
margin-rightright margin auto or <length> or <%>
margin-bottombottom margin auto or <length> or <%>
margin-leftleft margin auto or <length> or <%>
marginThis shorthand property sets the margin for all edges. auto, or <length>, or <%>

auto means browser would do calcluation.

The percentage values of margin are always derived from the width of the containing block.

 
<!DOCTYPE HTML> 
<html> 
    <head> 
        <title>Example</title>  
        <style type="text/css"> 
        img { 
            border: 4px solid black; 
            background: lightgray; 
            padding: 4px; 
            margin:4px 20px; 
        } 
        </style> 
    </head> 
    <body> 
        <img src="http://java2s.com/Book/HTML-CSSImages/star.png" alt="image"/> 
        <img src="http://java2s.com/Book/HTML-CSSImages/star.png" alt="background"/> 
    </body> 
</html>
  
Click to view the demo

The following CSS uses auto as the margin value:

 
<!DOCTYPE HTML> 
<html> 
    <head> 
        <title>Example</title>  
        <style type="text/css"> 
        img { 
            border: 4px solid black; 
            background: lightgray; 
            padding: 4px; 
            margin:auto; 
        } 
        </style> 
    </head> 
    <body> 
        <img src="http://java2s.com/Book/HTML-CSSImages/star.png" alt="image"/> 
        <img src="http://java2s.com/Book/HTML-CSSImages/star.png" alt="background"/> 
    </body> 
</html>
  
Click to view the demo
Home 
  HTML CSS Book 
    CSS  

Related: