CSS Box Model

CSS Margin

The CSS Margin property is used to create space outside an element’s border.
It controls the distance between an element and surrounding elements, helping to create proper layout and spacing on a webpage.

Margins are transparent and do not have a background color.

Syntax

css

selector {
    margin: value;
}

Example

css

p {
margin: 20px;
}

👉 This adds 20px space on all sides of the paragraph.

Attributes

PropertyDescriptionExample
marginSets margin on all sidesmargin: 10px;
margin-topSets top marginmargin-top: 20px;
margin-rightSets right marginmargin-right: 15px;
margin-bottomSets bottom marginmargin-bottom: 25px;
margin-leftSets left marginmargin-left: 10px;

Example

Complete CSS Margin Example

html

<!DOCTYPE html>
<html>
<head>
    <title>CSS Margin Example</title>
    <style>
        div {
            background-color: lightblue;
            margin: 20px;
            padding: 10px;
        }

        p {
            background-color: yellow;
            margin-top: 30px;
        }
    </style>
</head>
<body>

    <div>This is a div with margin.</div>

    <p>This paragraph has top margin.</p>

</body>
</html>

Output

Browser Output

html

<div>

Browser Support

Chrome
Firefox
Edge
Safari
Opera
IE9+
✅Yes✅Yes✅Yes✅Yes✅Yes✅Yes

Notes

  • Margin creates space outside the element
  • It is different from padding (which is inside spacing)
  • You can set margin for individual sides Supports shorthand values: margin: 10px 20px; (top-bottom, left-right)margin: 10px 15px 20px 25px; (top, right, bottom, left)
  • Margin can be set to auto for centering elements

Conclusion

CSS Margin is essential for controlling layout spacing between elements. It helps create clean, organized designs by ensuring proper distance and alignment across different parts of a webpage.