CSS Negative Margins - Part One

By: Zoe Gillenwater

Page 1 of 5

Set for printing

Next

Of all the pieces of the CSS box model, margins are probably the easiest to grasp. The margin is the transparent space outside the borders of a box that pushes other elements away from that box. But this is really only part of the definition. When you give a margin a negative value, it's a whole other ball of wax! This article will explain how negative margins work and begin to explore some of their uses. A following article will explain how negative margins can be used in float-based layouts to to achieve some interesting effects.

How Negative Margins Work

Margins are one of the few properties that can be given a negative value. A negative value essentially works in the reverse way that a positive value does. It's easiest to see visually, so check out these two divs:

These divs have the following CSS properties:

#div1 {
  width: 300px;
  height: 100px;
  border: 2px solid #f00;
}
#div2 {
  width: 300px;
  height: 100px;
  border: 2px solid #00f;
}

Note: If you look at the source code for this page, you will notice that there are left margins set on the two divs. This was done simply to make sure the boxes do not overlap the left CMX sidebar in later examples. The example code I've provided is for the hypothetical situation where the boxes are the only elements on the page.

Note that there is no margin set, so the margin values for each of the divs default to zero. This means the divs are moved zero pixels apart – they touch each other. Adding a positive margin value moves the divs apart by that amount:

#div1 {
  width: 300px;
  height: 100px;
  margin-bottom: 30px;
  border: 2px solid #f00;
}
#div2 {
  width: 300px;
  height: 100px;
  border: 2px solid #00f;
}

So if the blue div moves down from its original position by 30 pixels when the div above it has a bottom margin of 30 pixels, it follows that a value of -30 pixels will move the blue div up from its original position. Indeed, this is what happens:

#div1 {
  width: 300px;
  height: 100px;
  margin-bottom: -30px;
  border: 2px solid #f00;
}
#div2 {
  width: 300px;
  height: 100px;
  border: 2px solid #00f;
}

Note that the blue div now overlaps the div above it by 30 pixels! It's pretty simple: a box's positive margin value pushes surrounding content away from the box in the same direction as the margin, and a negative margin value pulls surrounding content over it.

I've used pixel values here for my example, but a negative margin value can take any sort of value, just like a positive margin.

Page 1 of 5 1 2 3 4 5 Next


download
Download Support Files


Downloads are disabled during your trial period.


Keywords
negative margins, margining, overlapping, overflowing, 3px bug, three pixel bug