The Definitive Guide to Using Negative Margins

Advertisement

Since the recommendation of CSS2 back in 1998, the use of tables has slowly faded into the background and into the history books. Because of this, CSS layouts have since then been synonymous with coding elegance.

Out of all the CSS concepts designers have ever used, an award probably needs to be given to the use of Negative Margins as being the most least talked about method of positioning. It’s like an online taboo—everyone’s doing it, yet no one wants to talk about it.

1. Setting the record straight Link

We all use margins in our CSS, but when it comes to negative margins, our relationship somehow manages to take a turn for the worse. The use of negative margins in web design is so divided that while some of us absolutely love it, there are also those who simply think it’s the work of the devil.

A negative margin looks like this:

#content {margin-left:-100px;}

Negative margins are usually applied in small doses but as you’ll see later on, it’s capable of so much more. A few things to note about negative margins are:

  • They are extremely valid CSS
    I’m not kidding on this one. W3C even says that, “Negative values for margin properties are allowed…” ‘Nuff said. Check out the article1 for more details.
  • Negative margins are not a hack
    This is especially true. It’s because of not understanding negative margins properly that it got its hackish image. It only becomes a hack if you use it to fix an error you made elsewhere.
  • It goes with the flow
    It does not break the flow of the page if applied to elements without floats. So if you use a negative margin to nudge an element upwards, all succeeding elements will be nudged as well.
  • It is highly compatible
    Negative margins are wholly supported across all modern browsers (and IE6 in most cases).
  • It reacts differently when floats are applied
    Negative margins are not your everyday CSS so they should be applied with care.
  • Dreamweaver doesn’t understand it
    Negative margins don’t show up in the Design View of DW. Why are you even checking your site in Design View anyway?

2. Working with negative margins Link

Negative margins are very powerful when used correctly. There are 2 types of scenarios where negative margins take center stage.

Negative Margins on Static Elements Link

Negative margins motion on static elements

A static element is an element with no float applied. The image below illustrates how static elements react to negative margins.

  • When a static element is given a negative margin on the top/left, it pulls the element in that specified direction. For example:
    /* Moves the element 10px upwards */
    
    #mydiv1 {margin-top:-10px;}
  • But if you apply it to the bottom/right, it doesn’t move the element down/right as you might think. Instead, it pulls any succeeding element into the main element, overlapping it.
    /* 
    * All elements succeeding #mydiv1 move up by
    * 10px, while #mydiv1 doesn’t even move an inch.
    */
    
    #mydiv1 {margin-bottom:-10px;}
  • If no width is applied, adding Negative Margins to its left/right pulls the element in both directions increasing its width. It’s here that the margin acts like a padding.

Negative Margins on Floated Elements Link

Consider this as our actual markup:

HTML

<div id="mydiv1">First</div>
<div id="mydiv2">Second</div>
  • If a negative margin is applied opposite a float, it creates a void leading to the overlapping of content. This is great for liquid layouts where one column has a width of 100% while the other has a definite width, like 100px.
    /* A negative margin is applied opposite the float */
    #mydiv1 {float:left; margin-right:-100px;}
  • If both elements are floated left and margin-right:-20px is applied to #mydiv1, #mydiv2 treats #mydiv1 as if it were 20px smaller in width than it actually is (thus, overlapping it). What’s interesting is that the contents of #mydiv1 don’t react at all and continue to retain its current width.
  • If the negative margin is equal to the actual width, then it overlaps it entirely. This is because margins, padding, borders, and width add up to the total width of an element. So if a negative margin is equal to the rest of the dimensions then the element’s width effectively becomes 0px.

3. Effective Techniques Link

Since we now know that applying a negative margin is valid CSS2 code, using it provides for some very interesting CSS techniques:

Making a single <ul> into a 3-column list Link

Splitting a list into 3 columns

If you have a list of items which are just too long to display vertically, why not divide them into columns instead? Negative margins let you do this without having to add any floats or additional tags. It’s amazing how it easily lets you divide the list below into 3 separate columns, like so:

HTML

<ul>
   <li class="col1">Eggs</li>
   <li class="col1">Ham<li>
   <li class="col2 top">Bread<li>
   <li class="col2">Butter<li>
   <li class="col3 top">Flour<li>
   <li class="col3">Cream</li>
</ul>

CSS

ul {list-style:none;}
li {line-height:1.3em;}
.col2 {margin-left:100px;}
.col3 {margin-left:200px;}
.top {margin-top:-2.6em;} /* the clincher */

By adding margin-top:-2.6em (twice the line-height of <li>) to .top, all elements move up in perfect alignment. Using a negative margin is more appropriate than applying relative positioning since you only have to apply it to the first of the new columns instead of to each <li> tag. Cool, huh?

Overlap for added emphasis Link

Phlashers.com

Overlapping elements on purpose is also a good design metaphor. It adds emphasis to specific elements since the overlapping effect creates the illusion of depth. A good example would be the comments section of Phlashers.com2, which uses an overlapping technique to draw attention to the number of comments a post has. Combine this with the z-index property and a little creativity and you’ve got it made.

Smashing 3D text effects Link

3D effects

Here’s a neat trick. Create Safari-like text, which are slightly beveled by creating 2 versions of your text in 2 different colors. Then use negative margins to overlap one over the other with a discrepancy of around 1 or 2 pixels and you’ve got selectable, robot-friendly beveled text! No need for huge jpegs or gifs which devour bandwidth like fat pigs.

Simple 2-column Layouts Link

Negative margins are also a great way to create simple 2-column liquid layouts where the sidebar has a preset width and the content has a liquid width of 100%

HTML

<div id="content"> <p>Main content in here</p> </div>
<div id="sidebar"> <p>I’m the Sidebar! </p> </div>

CSS

#content {width:100%; float:left; margin-right:-200px;}
#sidebar {width:200px; float:left;}

And there you have a simple 2-column layout record time. It works flawlessly in IE6 too! Now, to prevent #sidebar from overlapping the text inside #content, simply add

/* Prevent text from being overlapped */

#content p {margin-right:210px;}

/* It’s 200px + 10px, the 10px being an additional margin.*/

When used properly, negative margins can also provide what’s called a Flexible Document Structure which absolutely kicks tables in the face. Flexible Document Structure is an accessibility and SEO technique which allows you to arrange your markup in almost any order depending on your intentions. Tom Wright wrote an interesting article3 which discusses possible applications of negative margins in multicolumn layouts.

Nudging elements into place Link

This is the most common (and simplest) usage for negative margins. If you’re inserting a 10th div in a sea of 9 other divs and somehow it just won’t align properly, use negative margins to nudge that 10th div into place instead of having to edit the other 9.

4. Bugfixes Link

Using negative margins with floats sometimes pisses off older browsers. Some symptoms include:

  • Making links unclickable
  • Text becomes difficult to select
  • Tabbing any links disappears when you lose focus

Solution: Just add position:relative and it works!

My picture got cut-off Link

If you have the bad luck of using IE6 in the office, sometimes content will suddenly be cut-off when overlapping and floats are concerned.

Solution: Again, just add position:relative to the floated element and everything goes back to normal.

5. Conclusion Link

Negative margins have a place in modern web design because of its ability to position elements without any additional markup. With more users switching to more updated browsers (IE8 included), the future looks very bright for sites which rely on this technique.

If you have any unique experiences with negative margins, let me know by posting a comment.

6. Resources Link

More info on negative margins.

Footnotes Link

  1. 1 http://www.w3.org/TR/CSS2/box.html#margin-properties
  2. 2 http://phlashers.com/blog/?p=180
  3. 3 http://www.severnsolutions.co.uk/twblog/archive/2004/07/01/cssnegativemarginsalgebra
  4. 4 http://www.search-this.com/2007/08/01/the-positive-side-of-negative-margins/
  5. 5 http://www.severnsolutions.co.uk/twblog/archive/2004/07/01/cssnegativemarginsalgebra
  6. 6 http://www.mindfly.com/blog/post/2009/01/Get-Refreshed-Liquid-Layouts-With-Simpler-CSS-and-Without-A-Semantic-Mess.aspx
  7. 7 http://www.alistapart.com/articles/negativemargins/
  8. 8 http://www.w3.org/TR/1998/REC-CSS2-19980512/box.html#margin-properties
  9. 9 http://www.brainbell.com/tutorials/HTML_and_CSS/Using_Negative_Margins.htm
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15

↑ Back to top Tweet itShare on Facebook

John Imbong is a freelance designer who eats HTML for breakfast with a side of bacon (mmmm...bacon). He is also the CTO for Gourmee.com and is one of the founders of Phlashers.com. Follow John on twitter or through his portfolio site at Johnimbong.com.

Advertisement
  1. 1

    Awesome tutorial! I thought it was a hack or some illegal thing, now I can safely use it!

    0
  2. 2

    Negative margins should never be used to position elements. Use Top, Right, Bottom, or Left on either a relative or absolute positioned element instead.

    Margins should only be used for separation, not positioning.

    -34
  3. 3

    Margins should only be used for separation, not positioning.

    Why? Where is it written that using negative margins is illegal? In some cases, using position: relative/absolute isn’t appropriate or won’t work.

    If you use position: absolute, the element is taken out of the flow and other elements will occupy whatever space the positioned element would normally have unless you make allowances to move the following elements out of the way.

    If you use position: relative, then the element is moved, but the space that it would normally occupy is left behind, leaving a space in your layout. The only way to solve this is… wait for it… to use a negative margin to pull the following content back up into place.

    As the author says, using negative margins is a perfectly valid technique and if you’re not using it due to some obscure notion of what is right and what isn’t, then you’re depriving yourself of a very useful CSS tool.

    17
  4. 4

    Great article, I’ve never really understood why so many people are against the use of negative margins but this is a very clear and concise argument for their proper use.

    @Paul Grendek thats a pretty strange stance especially when you consider that positioned elements are not treated the same way across all browsers (IE6 isn’t dead yet). Positioning elements in that format also causes problems with fluid pages/content so they are somewhat inadvisable when it comes to good usability.

    @Mike they are nice for lists but be aware that you will have to know how many items are in the previous column to be able to correctly multiply the line height so its going to be a bit problematic for dynamic lists but otherwise a very handy trick.

    2
  5. 5

    Russell Heimlich

    July 27, 2009 1:20 pm

    Pownce.com used negative margins on an image to create interest. It was such a neat effect -> http://web.archive.org/web/20071224051229/http://www.pownce.com/

    1
  6. 6

    Alexandre Romero

    July 27, 2009 5:43 pm

    Negative margins always causes me lots of trouble. I prefer not use it if i have other options.

    2
  7. 7

    Great article!

    0
  8. 8

    Great guide, thank you!

    1
  9. 9

    Coming from Indesign it took me a while that there is a live outside the box in CSS. Same thing with negative positioning. Don’t forget to reset before you use negative values :)

    0
  10. 10

    Check out http://www.eaglerockschool.org – site I designed a few years back. We used negative margins out the wazoo on that one.

    0
  11. 11
  12. 12

    Great article, I don’t know why people are so scared about using negative margins, when used correctly they can make a site look one hundred per cent better than it did, it works particularly well with footers that you want to blend in.

    One thing, remember that z-index:; is a handy tool when it comes to ;).

    0
  13. 13

    Multi-column lists looks really handy, thanks!

    0
  14. 14

    Great article. Works great in Firefox but not in IE 6…. Any trick for this one?

    0
  15. 15

    I never knew there was much of any debate on the use of negative margins. I always used them with no issues, just following the spec. I tend to let others debate these things endlessly. The rest of us have work to do. Great piece, John.

    0
  16. 16

    Be very careful about saying “just add position:relative;.” IE6 and IE7 will not respect z-index values for relatively positioned elements; they are always put at the top of the stack. This will cause problems if they ever overlap with pull-down/ fly-out elements like menus, as the menu will always be beneath them. Relative positioning is very useful, but needs to be used with caution.

    0
  17. 17

    Good idea with the beveled text look.

    0
  18. 18

    @John Faulds: absolutely. thats why i use negative margins all the time.

    @Paul Gendek: how do you solve these spacing problems John Faulds speaks of without using negative margins?

    0
  19. 19

    IE6 and IE7 will not respect z-index values for relatively positioned elements

    Yes they do, they just don’t inherit them correctly from their parents but instead need to be stated explicitly. See Anne van Kesteren’s article for more details. So all you need to do is remember to declare z-index on relatively positioned elements where necessary and you’ll be fine.

    And just a comment on the bevelled text technique: there’s two reasons why you’d be better off not using that technique:

    1. you need to have the same piece of text written out twice in the source which means it’ll appear twice on the page if styles are off and will be read out twice by screenreader users (which would be very annoying).
    2. the same effect can be achieved using text-shadow which is now supported by FF3.5, Opera 10 and all Webkit browsers.

    -1
  20. 20

    hm my site uses a negative margin to make a sidebar, just two divs in to a wrapper+subwrappers (and ofc a reset.css)
    i already tested:
    win: ie6, ie7, ie8, firefox 3.5, safari 4, opera 9.64
    mac: safari 4, opera 9, opera 9.64, firefox 3.5

    all of them display almost the same, but even reseting everything you still have some pixels difference, btw i’m using “em” to the width/min-width

    any fix for this small diferences (its like 1 or 2 px) or any idea what element is causing this? there’s a difference (specially in opera) even with fixed width + negative margins

    0
  21. 21

    Good post. I have used negative margin without much issue in most of my projects. Difficulty in selecting text was an issue and had to find out the solution by trial and error.

    0
  22. 22

    Wow the beveled text effect is an amasing idea! Never would have thought about it!

    0
  23. 23

    Great article. I’ve never looked into negative margins before, just started using it gradually as I found it handy.

    0
  24. 24

    A Website Designer

    July 27, 2009 3:31 pm

    I am just pleased to see in black and white negative margins are not a hack! :-)

    1
  25. 25

    i use negative margins in The Guidon website. I used to think it’s weird to have them :))

    0
  26. 26

    Negative margins can also be helpful in multi-column layouts, if you want to reorder the columns without changing the HTML source, for example to keep your main content first in source order.

    Another common use is when you want to keep some text in the HTML source for accessibility or SEO reasons, but hide that text on-screen, typically because you’re using some sort of background-image replacement technique.

    0
  27. 27

    very useful, I am trying to implement it my own website

    0
  28. 28

    great! great! great!

    thanks!

    0
  29. 29

    I must admit, I pretty much avoided negative margins in the past for no particular reason. Maybe it was a negative value for a property that got me a bit ‘suspicious’ :) I did use negative margins when there was no other way to do the job, but after reading this article I will use this positioning technique just like any other. Thank you SM! :)

    1
  30. 30

    Great article! I feel more comfortable using negative margins – I was using them but thought it was risky :)

    1
  31. 31

    Great article. I didn’t know that people don’t speak about negative margin!

    I use negative margin for some elements in the background that I don’t want to be scrollable. For exemple, if I have a content column of width 700px, and some elements at the left and at the right in the background, I want that if I reduce the window size, there would have no horizontal scroll for them.

    At the left, this elements have a negative margin-left to go at the right place, And so, the browser doesn’t count them as elements to be scrollable. Then small screen with a window open at 700px width won’t see background decorative elements that are not usefull to read content, and they won’t have the horizontal scroll.

    I think this technic is nice to handle some wide decorative background, if only it would work also with the margin-right. Unlucky the horizontal scroll apears even with a simple negative margin-right. Any idea for the right side?

    Thanks for this article

    0
  32. 32

    Sig. Tolleranza

    July 27, 2009 10:45 pm

    Really great tutorial. Thanks a lot!

    0
  33. 33

    Cool tips,
    Thanks a lot. Now, i can use negative margin where i need.

    0
  34. 34

    the multicolumn list trick is cool!
    thanks a lot

    0
  35. 35

    Felix Buenemann

    July 27, 2009 11:49 pm

    I use negative margins to line up column text in multi column layouts but keep headings above the text. Apply a margin-top on all columns, then use a negative margin-top of same amount on the first heading in that column with a class like h1.first-header.

    1
  36. 36

    Negative margin is your friend! :)

    0
  37. 37

    Lovely article :)

    0
  38. 38

    Concerning the fantastic beveled text trick:

    I’ve tried it now, and it “works” in FF, Chrome and Safari, BUT it differs with around 6px or so in IE8 and Opera.

    Any workaround to avoid this without hacking (have tried position:relative already).
    I’ve also added: * {margin:0;padding:0;} to the css.

    0
  39. 39

    Great article.

    Negative margins can be used to create flexible cross-browser equal-height columns as described here: http://socialgeek.be/blog/read/flexible-equal-height-columns

    0
  40. 40

    I often wonder how afraid are the authors when it comes to subjects which are…let’s say a little more discussed than normal. Do they ever fear an angry CSS/HTML mob ready to burn you at the stake? ;-)

    Seriously almost all hotly discussed topics have their place in a web designers tool bag and this works really well and I do use it. As long as it is only one tool in many and not the solution to all life’s problems it will always be very useful.

    0
  41. 41

    Hi,
    thanks for the article. I had the question about validity of negative margin since if first used them. Thanks for giving clarification.

    0
  42. 42

    Simple and great.. Thanks for effort.

    0
  43. 43

    Dylan Harrington

    July 28, 2009 1:57 am

    pretty neat article. fyi there are a few typos in the 3 column example (html part).

    0
  44. 44

    Thanks for the informative article.

    0
  45. 45

    Thanks for the short and great article!

    0
  46. 46

    I never understood the behavior of “position:relative”. It annoys me until I discovered negative margins were doing the trick ;)

    0
  47. 47

    Very interesting article !
    It has changed a little bit my opinion (very “negative”) on negative margins. To my mind it’s not necessary to put negative margins when we can avoid it. But, your examples make me realized that is sometimes usefull (example for the display of the ul list).
    Thanks for sharing your knowledge about CSS.

    0
  48. 48

    3-column list technique was most unexpected for me. Thanks!

    0
  49. 49

    great article on a feature of css that many consider to be a bug…

    0
  50. 50

    Thanks! Can’t wait to use the 3colomn list technique!

    0

↑ Back to top