HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

CSS Margins

Margins are used to create space around elements, outside of any defined borders. The margin property clears an area outside the border of an element.


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: Top Margin

40px Top Margin Applied
p {
    margin-top: 40px;
    margin-bottom: 20px;
    margin-left: 50px;
    margin-right: 30px;
}

Margin Shorthand

To keep your CSS code clean, you can specify all margin properties in one single property. The order of the values is: Top, Right, Bottom, Left.

/* Four values: Top, Right, Bottom, Left */
margin: 25px 50px 75px 100px;

/* Three values: Top, Right/Left, Bottom */
margin: 25px 50px 75px;

/* Two values: Top/Bottom, Right/Left */
margin: 10px 20px;

/* One value: All four sides */
margin: 20px;

The Auto Value

If you set the margin property to auto, it will horizontally center an element within its container. The element will then take up the specified width, and the remaining space will be split equally between the left and right margins.

margin: auto; centered
div {
    width: 300px;
    margin: auto; /* Centers the box horizontally */
}

Negative Margins

Unlike padding, margins can have negative values. This allows you to pull elements closer together or even make them overlap.

p {
    margin-top: -10px; /* Pulls the element up */
}

Margin Collapse

Sometimes the top and bottom margins of elements are collapsed into a single margin that is equal to the largest of the two. This does not happen on left and right margins!

Note: Only vertical (top/bottom) margins of adjacent elements will collapse, never horizontal.