CSS Tutorial - CSS Margin








Margin is space between the element border and its surroundings. This includes other elements and the parent element.

The following list has the description for the margin properties.

  • margin-top
    Sets the margin for the top edge.
    Value: auto length %
  • margin-right
    Sets the margin for the right edge.
    Value: auto length %
  • margin-bottom
    Sets the margin for the bottom edge.
    Value: auto length %
  • margin-left
    Sets the margin for the left edge.
    Value: auto length %
  • margin
    This shorthand property sets the margin for all edges in a single declaration.
    Value: 1 - 4 auto length %

The percentage values are always derived from the width of the containing block, even when used for padding the top and bottom edge.

The following code adds Margin to Elements.

<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
img {<!-- w  w w. jav  a  2s . c  o  m-->
  border: 4px solid black;
  background: lightgray;
  padding: 4px;
  margin: 4px 20px;
}
</style>
</head>
<body>
  <img src="http://www.java2s.com/style/download.png" alt="small  banana">
  <img src="http://www.java2s.com/style/download.png" alt="small  banana">
</body>
</html>

Click to view the demo

For an inline element, its margin isn't displayed at the top and bottom edges.





Margin Shorthand property

The margin property can have from one to four values.

margin: 2px 5px 7px 9px;
    top margin is 2px
    right margin is 5px
    bottom margin is 7px
    left margin is 9px

margin: 2px 5px 7px;
    top margin is 2px
    right and left margins are 5px
    bottom margin is 7px

margin: 2px 5px;
    top and bottom margins are 2px
    right and left margins are 5px

margin: 2px;
    all four margins are 2px




Property Description CSS
margin-bottom Set the margin for bottom1
margin-left Set the left margin1
margin-right Set the right margin1
margin-top Set the top margin1
margin Set margin for four directions1