CSS Margins


Margins are like empty areas around things on a webpage. They help make things have some space around them, even if there's no border around those things.


This element has a margin of 50px from all four sides.

CSS Margins

The CSS margin help make space around elements, outside of their borders.

With CSS, you can fully control the spaces around an element. You can use properties to set the space on each side of the element – the top, right, bottom, and left sides.


Margin - Individual Sides

CSS has options for setting the space around each side of an element, which is called the margin.

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

All margin settings can use these options:

  • auto - the web browser figures out how much space to leave around something.
  • length - We can specify margin in px, pt, cm, etc.
  • % - Indicates a margin in % of the width of the containing element
  • inherit - Shows that the space at the edge should be taken from the main part above it.

Margin - Shorthand Property

You can write shorter code by using only one property to adjust all the margin settings..

The margin "property" is like a shortcut for talking about a bunch of special margin things. These margin things include:

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

If the margin property has four values:

  • margin: 25px 50px 75px 100px;
    • top margin is 25px
    • right margin is 50px
    • bottom margin is 75px
    • left margin is 100px

If you use three values for the margin property:

  • margin: 25px 50px 75px;
    • top margin is 25px
    • right and left margins are 50px
    • bottom margin is 75px

If you have two values for thecode class="ppt-codespan">margin property:

  • margin: 25px 50px;
    • top and bottom margins are 25px
    • right and left margins are 50px

The auto Value

To put something in the middle of its box from side to side, you can use the "margin" style and set it to "auto".

The object will use the given width and share the leftover space equally between its left and right sides.


The inherit Value

This example allows the left margin of the paragraph with class "ex1" to inherit from its parent element, which is a <div>.


Margin Collapse

Margins at the top and bottom of objects can sometimes combine to form one margin. This single margin will be as big as the larger of the two original margins.

This doesn't occur on the sides, only at the top and bottom edges!

In the provided example, the main heading (<h1>) has extra space at the bottom of 50 pixels, while the subheading (<h2>) has a gap of 20 pixels at the top.

Using our regular understanding, we might think that the space between the <h1> heading and the <h2> heading would be 70 pixels in total (50 pixels + 20 pixels). However, because of something called margin collapse, the real space is only 50 pixels.