Margin

Introduction to Margin

Margin refers to the space around the outside of an element's border in web design. Here are some key points to note:

  • Part of the CSS Box Model: Margin is crucial for controlling the layout and spacing between elements.

  • Affects Element Positioning: Proper use of margins can prevent elements from overlapping or being too close.

  • Customizable Size: Margins can be set to specific values or percentages, providing flexibility in design.

  • Independent Sides: Margins can be applied to the top, bottom, left, and rightsides independently or all at once.

  • Auto Value Usage: Setting margin to auto can help center elements, especially within containers.

Understanding margins helps ensure a cleaner and more user-friendly layout.

Possible Values (For Each Sides)

Value
Unit
Description

Any Number

px

Absolute offset in pixels.

Any Number

rem

Offset relative to the font-size of the root element.

Any Number

%

Offset relative to the parent element's width.

Any Number

vw

Offset relative to 1% of the viewport width.

N/A

auto

N/A

unset

Removes any set margin, reverting to inherited if possible, otherwise to the initial value

N/A

initial

Resets the margin to the default value defined by the browser

N/A

inherit

Inherits the margin value from the parent element.

Example

  1. lets explain margin with the help of the following example. We have a single text input field along with a submit button. First picture shows them without margin and the second one is with margin = 5 px;

After setting margin left of button .

Last updated