CSS

CSS Margins


CSS Margin Properties

  • The CSS margin properties are used to generate space around elements.
  • The margin properties set the size of the white space OUTSIDE the border.

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:



 <!DOCTYPE html>
<html>
<head>
<style>
p {
    background-color: yellow;
}

p.ex {
    border:1px solid red;
    margin-top: 100px;
    margin-bottom: 100px;
    margin-right: 150px;
    margin-left: 80px;
}
</style>
</head>
<body>

<h2>Using Individual margin Properties:</h2>

<p>This is a paragraph with no specified margins.</p>
<p class="ex">This paragraph has a top and bottom margin of 100px, a left margin of 80px, and a right margin of 150px.</p>

</body>
</html>

Margin - Shorthand Property

To shorten the code, it is possible to specify all the margin properties in one property.
The margin property is a shorthand property for the following individual margin properties:

  • margin-top
  • margin-right
  • margin-bottom
  • margin-left

Example:


<!DOCTYPE html>
<html>
<head>
<style>
p {
    background-color: yellow;
}

p.ex {
    border:1px solid red;
    margin: 100px 150px 100px 80px;
}
</style>
</head>
<body>

<h2>Using The margin Shorthand Property:</h2>

<p>This is a paragraph with no specified margins.</p>
<p class="ex">This paragraph has a top and bottom margin of 100px, a left margin of 80px, and a right margin of 150px.</p>

</body>
</html>

 

Use of 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 red;
}
</style>
</head>
<body>

<h2>Use of the auto Value</h2>
<p>You can set the margin property to auto to horizontally center the 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:</p>

<div>
This div will be centered because it has margin: auto;
</div>

</body>
</html>