CSS Margins



Margins are used to create space around elements, outside of any defined borders.

Example
        

      <!DOCTYPE html>
      <html>
      <head> 
      <style> 

      div  {
        margin:70px;
        border:1px solid #4CAF50;
            }
  
      </style> 
      </head> 
      <body> 

      <h2>CSS Margins</h2>

      <p>This property is used to add rounded borders to an element:</p>

      <div>AIT Academy of Information Technology</div>
     
  
          </body>
          </html>
                
              
Result:
Example Image

Margin - Individual Sides


CSS has properties for specifying the margin for each side of an element:

  • margin-top
  • margin-right
  • margin-bottom
  • margin-left

  • Example

    Set different margins for all four sides of a <p> element:

            
    
          <!DOCTYPE html>
          <html>
          <head> 
          <style> 
    
          div  {
            border:1px solid black;
            margin-top:100px;
            margin-bottom:100px;
            margin-right:150px;
            margin-left:1px solid #4CAF50;
            background-color:yellow;
                }
      
          </style> 
          </head> 
          <body> 
    
          <h2>Using individual margin properties</h2>
    
          <div> AIT Academy of Information Technology
    AIT Academy of Information Technology
    AIT Academy of Information Technology</div>
    </body> </html>
    Result:
    Example Image

    Margin - Shorthand Property


    To shorten the code, it is possible to specify all the margin properties in one property.

    The margin property is a shorthand property for the following individual margin properties:

    Example

    Use the margin shorthand property with four values: <p> element:

            
    
          <!DOCTYPE html>
          <html>
          <head> 
          <style> 
    
          div  {
            border:1px solid black;
            margin:25px 50px 75px 100px;
            background-color:yellow;
           
                }
      
          </style> 
          </head> 
          <body> 
    
          <h2>The margin shorthand property - 4 values</h2>
    
          <div> AIT Academy of Information Technology
    AIT Academy of Information Technology</div>
    <hr> </body> </html>
    Result:
    Example Image