CSS Margins || Bcis Notes

CSS Margins

The margin properties are used to create space around elements, outside of any defined borders. It is possible to use negative values to overlap content. The values of the margin property are not inherited by the child elements. With CSS, you have full control over the margins. CSS has properties for specifying the margin for each side of an element:

Margin – Individual Sides

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

All the margin properties can have the following values:

  • auto – the browser calculates the margin
  • length – specifies a margin in px, pt, cm, etc.
  • % – specifies a margin in % of the width of the containing element
  • inherit – specifies that the margin should be inherited from the parent element

NOTE:  Negative values are allowed

 

CODE:

 

Result:

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                                                                                                                                                                                        So, here is how it works:
  • margin: 50px 70px 85px 50px;
  • top margin is 50px
  • right margin is 70px
  • bottom margin is 85px
  • left margin is 50px

 

CODE:

 

Result:

 

The auto Value
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.

CODE:

 

Result:

The inherit Value
This example lets the left margin of the <p class=”ex”> element be inherited from the parent element (<div>):

CODE:

 

Result:

 

Margin Collapse:
The top and bottom margins of elements are sometimes collapsed into a single margin that is equal to the largest of the two margins. This does not happen on the left and right margins! Only the top and bottom margins!

CODE:

 

Result:

 

In this example, the h1 element has a bottom margin of 50px and the h2 element has a top margin of 20px. Then, the vertical margin between h1 and h2 should have been 60px (50px + 10px). However, due to margin collapse, the actual margin ends up being 50px

 

 

 

 

You may also like: CSS Borders

Leave a Comment

Your email address will not be published. Required fields are marked *