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

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

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

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

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

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

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

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

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

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

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

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

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

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

More info on negative margins.

Footnotes

  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

    I LOVE you guys for this. This is the exact article I’ve been looking for. I’m good at everything in CSS except negative values.

    0
  2. 102

    Thanks for this. This really clears up negative margins and how they should be used.

    0
  3. 203

    Thank you so much. I had exhausted a ton of css solution to try to get my design cross-browser compliant and the solution was “position:relative;”.

    Never would have thought of that!

    0
  4. 304

    I’m thankful for this article but, this is sooo complicated…I swear I could cry right now.

    -1
  5. 405

    position; relative: THANK YOU!!!

    0
  6. 506

    Great article!

    One question though:
    I used to use a relative DIV “wrapper” to embed all content. In that case, if the browserscreen was smaller than the defined Width for the wrapper, on the right side of the screen part of the website became hidden.
    With the negative margin option though, if the browserscreen becomes smaller than the defined Width of the website, then on BOTH left and right side of the browserscreen content is hidden.

    How do I make sure content on the LEFT side of the browserscreen is NOT hidden (when using negative margins)?

    -1
  7. 607

    very nice and helpful article

    -1
  8. 708

    Hi,

    Has anybody experienced problems with Chrome not rendering a negative margin-top correctly?

    Chris

    0
  9. 809

    Just because you can, doesn’t mean you should! Of all the things on the list of Do’s, this is the only one that I disagree with. It’s an amature move, seriously and I suggest you stop doing it and learn how to use positioning. In addition it’s a maintenance nightmare and if you do it in enterprise applications, you’re going to cause quite a headache for those who have to maintain the code after you. Just avoid it, you’ll look like a hack!

    2
  10. 910

    I got the same bug here… Chrome is not showing a negative top margin correctly. The worse is that it only happens sometimes, and when it does, a browser refresh solves the problem. I’m looking for a workaround; suggestions are welcome.

    2
  11. 1011

    I have developed more than 20 xhtml pages and never had a problem using negative margins. IMHO negative margins are a time saver in most cases, in other cases they can really help you if you are using some ‘hard to position’ script, well even when developing with javascript negative margins can be very useful.

    I don’t understand the people that prohibits the use of negative margins, just typing a -1 you can easily fix a wrong positioned element. And it is valid!

    0
  12. 1112

    nice man it is very helpful to me for doing work…………………

    -1
  13. 1213

    So you did, did you? I won’t tell.

    0
  14. 1314

    It’s always best to code off the bat in Code View then preview using real browsers. Think of it as web designer training except you’re both the student and the teacher. FYI, I use Dreamweaver for all my projects whether it’s a static site, WordPress Theme or Drupal Theme.

    0
  15. 1415

    If you liked the beveled text effect, it’s much better now to use the new CSS 3 implementation of the text-shadow property.

    It goes like this: #thistext {text-shadow:1px 1px #000;}

    Nice and simple.

    -2
  16. 1516

    No, no, no, no, no! Sorry, but the examples are really, really bad practice.
    You seriously think it’s a good idea to position elements using negative margins?

    It doesn’t matter how “valid” it is, it’s still the “wrong” way of using CSS. Margins are used to create space between the bounding box of an element and its content, ignoring background. Much like padding, but outside the box, so to speak.

    Even though this is an “old” article, please put a disclaimer on top stating there are better ways to achieve the effects mentioned, using positioning and CSS3 (for the beveled text example).

    -2
  17. 1617

    John, thanks for the great article! This has been very helpful in my efforts to hack the WordPress Twenty Ten theme into a custom theme for Hale College. I’m looking forward to digging through some more of your articles. Cheers!

    1
  18. 1718

    Thanks man. Excellent article. I’ve been looking for a solution to the negative margin-left in I.E. and I only found it in your post. I put position-relative as you told. Thanks a lot.

    1
  19. 1819

    Thanks from Norway!

    0
  20. 1920

    Thanks for the article John, margin negative is really a life-saver. Shared the article! Regards

    0
  21. 2021

    Hi guys,

    Hoping someone’s still checking these comments.

    My issue is that my negatively margined (?) div is ‘covering’ the links of the div underneath. I need links to work in both divs, and z-index doesn’t seem to be working at all. Neither divs are floated, just the bottom div pulled up a bit with a negative margin on top and it’s ‘covering’ links of the div below it.

    Any thoughts? Thanks!

    The site in question is here: http://dawsondental.ca

    0
  22. 2122

    I have not seen such a good article on negative margins……Thanks John!

    0
  23. 2223

    DEAR LORD THANK YOU. I’m designing a site for a class I’m taking and I have a protruding image that extends down into my navbar. I used {margin-top:-30px;} to get the #nav to connect to the image and achieve the overlap. Unfortunately, this killed the links in #nav. I added {position:relative;} to each of the divs involved, but it was still broken in IE. I added relative positioning to the list and anchor elements (which are floated) and voila!

    You spoke in a language I could understand and I thank you good sir!

    0
  24. 2324

    Also be aware that if a list item text breaks over two lines, then the negative margin of 3 * line height isn’t going to work.

    0
  25. 2425

    OK, I doubt I get a response four years after this was written, but I have an issue with a nav that I want fixed on the page when you scroll down. I have a negative margin that is causing my fixed div to disappear in Safari. When I set the position to relative for the div, it shows up in Safari but now it scrolls with the rest of my site.

    So can I have the best of both worlds somehow? A fixed positioning that still jibes with Safari??

    0

↑ Back to top