Facebook Pixel

CSS Margin

The margin is the space outside an HTML element. It provides external spacing and helps to separate two or more elements from each other.

Consider the image: cwh tutorial image

Here, the space outside the border is the margin.

Syntax:

selector {
    margin: value;
}

The margin property can be applied in different ways:

Method 1: Equal margin on all sides

selector {
    margin: value;
}

This applies the same margin to all four sides (top, right, bottom, and left).

Example:

<html lang="en">
<head>
    <style>
        #p1 {
            border: 2px solid purple;
        }
        #p2 {
            margin: 12px;
            border: 2px solid red;
        }
    </style>
</head>
<body>
    <p id="p1">CodeWithHarry (without margin)</p>
    <p id="p2">CodeWithHarry (with margin)</p>
</body>
</html>

Note: Margin values can be given in different units such as pixels (px), em, rem, percentages (%), or auto.

cwh tutorial image

Method 2: Vertical and horizontal margins

selector {
    margin: value1 value2;
}
  • value1 → vertical margin (top and bottom)
  • value2 → horizontal margin (left and right)

Example:

<html lang="en">
<head>
    <style>
        #p1 {
            border: 2px solid purple;
        }
        #p2 {
            margin: 20px 50px;
            border: 2px solid red;
        }
    </style>
</head>
<body>
    <p id="p1">CodeWithHarry (without margin)</p>
    <p id="p2">CodeWithHarry (with margin)</p>
</body>
</html>

cwh tutorial image

Tip: Use the browser’s inspect tool to check applied margins visually.

Method 3: Individual margins for each side

selector {
    margin: value1 value2 value3 value4;
}

In this method, each value represents the margin of individual sides (top, right, bottom, left).

  • top: value1
  • right: value2
  • bottom: value3
  • left: value4

Example:

<html lang="en">
<head>
    <style>
        #p1 {
            border: 2px solid purple;
        }
        #p2 {
            margin: 15px 30px 25px 50px;
            border: 2px solid red;
        }
    </style>
</head>
<body>
    <p id="p1">CodeWithHarry (without margin)</p>
    <p id="p2">CodeWithHarry (with margin)</p>
</body>
</html>

cwh tutorial image

In this example, the margins are:

  • top: 15px
  • right: 30px
  • bottom: 25px
  • left: 50px

Both padding and margins are essential in CSS for managing spacing. While padding adds space inside the element (between content and border), margins add space outside the element (between elements themselves). Used together, they help make a web page look clean, balanced, and visually appealing.