CSS Margin

CSS Margin

The margin property defines the space around an HTML element. It is possible to use negative values to overlap content.

We have the following properties to set an element margin.

All the margin properties can have the following values:

Example:

    <!DOCTYPE html>
<html>
<head>
<style>
p {  
    background-color: pink;  
}  
p.ex {  
    margin-top: 50px;  
    margin-bottom: 50px;  
    margin-right: 100px;  
    margin-left: 100px;  
}  
</style>
</head>
<body>
<p>This paragraph is not displayed with specified margin.</p>
<p class="ex">This paragraph is displayed with specified margin.</p>
</body>
</html>
Try it with the Editor

Margin: Shorthand Property

CSS shorthand property is used to shorten the code. It specifies all the margin properties in one property.

There are four types to specify the margin property. You can use one of them.

  1. margin: 25px 50px 75px 100px;
  2. margin: 25px 50px 75px;
  3. margin: 25px 50px;
  4. margin 25px;
1. margin: 25px 50px 75px 100px;
2. margin: 25px 50px 75px;
3. margin: 25px 50px;
4. margin 25px;

The auto Value

You can set the margin property to auto to horizontally center the element within its container.

Example:

    <!DOCTYPE html>
<html>
<head>
<style>
div {
    width:300px;
    margin: auto;
    border: 1px solid;
}
</style>
</head>
<body>
<h2>Use of the auto Value.</h2>
<div>
This div will be centered because it has margin: auto;
</div>
</body>
</html>
Try it with the Editor

The inherit Value

This example lets the left margin be inherited from the parent element:

Example:

    <!DOCTYPE html>
<html>
<head>
<style>
div.container {
    border: 1px solid;
    margin-left: 100px;
}
p.one {
    margin-left: inherit;
}
</style>
</head>
<body>
<h2>Use of the inherit value.</h2>
<p>Let the left margin be inherited from the parent element:</p>
<div class="container">
<p class="one">This is a paragraph with an inherited left margin (from the div element).</p>
</div>
</body>
</html>
Try it with the Editor