Margin and padding explained; CSS tutorial

Let’s step back and start at the basics, in order to understand these element properties it’s best to remove any background confusion. Internet browsers (eg. Internet Explorer, Firefox, Camino, …) typically apply their own default values to page elements, this is done to create a standard experience across non-styled pages. We need to disable these default values as they differ across browsers, then I can teach you how these properties influence how elements are rendered.

To remove the default browser styles from the red and blue boxes below you would type in CSS:

.red {
margin:0;
padding:0;
}
.blue {
margin:0;
padding:0;
}

Default state of elements

Margin
The larger the margin the further apart an element will be positioned in that given direction.

Example: In the below illustration a margin-bottom style of 2 blocks has been applied to the top (red) element, this creates a space of 2 blocks below the bottom (blue) element.

To apply a bottom margin to the red element you would type in CSS:

.red {
margin-bottom:20px;
}

Bottom margin applied to the top (blue) element.

Padding
The larger the padding the greater expansion of that element in that given direction.

Example: In the below illustration a padding-bottom style of 2 blocks has been applied to the top (red) element, this expands the red element vertically 2 blocks in turn pushing the the bottom (blue) element down 2 blocks.

To apply a bottom padding to the red element you would type in CSS:

.red {
padding-bottom:20px;
}

Bottom padding applied to the top (blue) element.

Zero (0) shortcut
0px
can be shortened to 0; however all ‘real’ numbers must be followed by a metric, for example:

  • px
  • em
  • %

Squish properties together
margin-top: 50px;
margin-right: 4em;
margin-bottom: 10%;
margin-left: 0;

can be shortened to…

margin: 50px 4em 10% 0;

Getting lazy? Maybe productive
padding:1.2em 5px;

is interpreted as…

padding:1.2em 5px 1.2em 5px;

Leave a Comment

Before you comment - Do you have a support request? If so, this is not the right place to post it. Please submit support requests for Premium Plugins on the Support page and in the community Support Forums for free Plugins.

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