đŸ’¡ Tip: Login now to track your course progress and unlock your downloadable certificates instantly!

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
selector {
    margin: value;
}
Example
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
<!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

The <div> will have space around it (20px on all sides)
The <p> will have extra space above it (30px)
Elements will not touch each other due to margin spacing

Browser Support

Chrome
Chrome
Firefox
Firefox
Edge
Edge
Safari
Safari
Opera
Opera
IE
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.

Sign In Form

Use your email and password to sign in

Provide your email and we will send you a password reset link.

Don’t have an account, signup here : 

HTML5 & CSS3

Tools and Tutorials

Registration Form

Signup to track your record and much more.

We have sent you an email with a registration link. Please click the link to verify your email address, or enter the 6-digit OTP provided in the email.

Didn't receive the OTP. Regenerate OTP Resend