CSS - margin



The margin property is a shorthand property which sets the width of the margins on all four sides of an element.

Possible Values

  • length − Any length value.

  • percentage − The margin's width is calculated with respect to the width of the element's containing block.

  • auto − Sets the values for all four margins to be automatically calculated.

Applies to

All the HTML elements.

DOM Syntax

object.style.margin = "5px"

CSS margin - Basic Example

Following example demonstrates the use of CSS property margin

<html>
<head>
<style>
   p {
      background-color: rgb(201, 238, 240);
      border: 1px solid black;
      width: fit-content;
   }

   .margin-one {
      margin: 30px;
   }

   .margin-two {
      margin: 20px 5%;
   }

   .margin-three {
      margin: 10px 2% -5px;
   }

   .margin-four {
      margin: 10px 2% -5px auto;
   }
</style>
</head>
   
<body>
   <p class="margin-one">
      all four margins will be 30px.
   </p>
   
   <p class="margin-two">
      top and bottom margin will be 20px, left and right margin will be 5% 
      of the total width of the document.
   </p>
   
   <p class="margin-three">
      top margin will be 10px, left and right margin will be 2% of the 
      total width of the document, bottom margin will be -5px.
   </p>
   
   <p class="margin-four">
      top margin will be 10px, right margin will be 2% of the total 
      width of the document, bottom margin will be -5px, left margin 
      will be set by the browser.
   </p>
   
</body>
</html> 
Advertisements