Home Videos Exercises MCQ Q&A Quiz E-Store Services Blog Sign in Appointment Payment

CSS Margins

Margins are used to create space around elements, outside of any defined borders.


CSS Margins

The CSS margin properties are used to create space around elements, outside of any defined borders.

With CSS, you have full control over the margins. There are properties for setting the margin for each side of an element (top, right, bottom, and left).

CSS margins create space around an element, pushing it away from other elements nearby.

CSS Margin property is used to define the space around elements. It is completely transparent and doesn't have any background color.


Margin - Individual Sides

CSS has properties for specifying the margin for each side of an element:
  • 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

Margin- Shorthand Property

To shorten the code, it is possile to specify all the margin properties in one property.

The margin property is shorthand property for the following individual margin properties.

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

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.

Example:
div{
width:350px;
margin:auto;
border:1 px solid black;
}


Key points of CSS Border

1. Margin Shorthand

The margin property can set all four sides (top, right, bottom, left) in a single line.

Example:
div{ margin: 10px 15px 20px 25px; /* top, right, bottom, left */ }


2. Individual Margins

Define each side’s margin separately with margin-top, margin-right, margin-bottom, and margin-left.

Example: div { margin-top: 20px; margin-right: 10px; }


3. Auto Margins

Setting margin: auto; centers the element horizontally within its container (useful for block elements with a defined width).

Example:
div { width: 50%; margin: auto; }


4. Negative Margins:

Margins can be negative, which pulls the element closer to surrounding elements.

Example:
div { margin-top: -10px; }


5. Margin Collapsing:

Adjacent vertical margins (top and bottom) between elements may "collapse" into a single margin equal to the larger of the two. This only happens with vertical margins, not horizontal ones.


6. Percentages:

Margins can be set using percentages, relative to the width of the containing element.

Example:
div { margin-left: 5%; }


7. Inheritance:

Margins do not inherit from parent elements; they apply only to the specific element they are defined on.