Fix: jQuery sliding jumps

When using the jQuery slide functions like slideDown() or slideToggle() you might experience some jumping motion of the sliding html containers what is not pleasing to the eye. There are a lot of bugfix suggestions out there on the web but they did not work out for me. I wanted to built an accordion like menu that shows only relevant UI-elements.

I tried to put a fixed width or height on the involved HTML containers of my menu, but that didn’t help. Then I further experimented with 1px paddings and invisible borders to avoid the jumping. This helped but I did not understand why and I found this solution not very effective as it messes up my CSS. After some long hours of trial and error I finally found that the reason for this behaviour is the collapsing of margins in HTML/CSS. This problem is well described here. It happens for adjacent elements and for nested elements (parent > child) as well. If those elements have margins defined in the same direction these margins are collapsed into one margin that is big enough to satisfy both elements. Take an upper div container with margin-bottom of 10px and a lower div container with a margin-top of 20px. What do you get rendered in your browser? A single margin between both containers that is 20px high. So both margins are not added together and you don’t get the expected 30px gap between both containers. That is known as margin collapse.

In sliding motion we run into this problem when defining margin-top or margin-bottom on the sliding HTML container and on the surrounding elements as well. That is because the jQuery does the sliding animation without any margins being collapsed. When animation has finished your browser collapses the margins finally what results in a jumpy motion.

I found some interesting articles how to avoid this, but none solution worked for all of my cases. I finally found this article giving a strict approach how to use margins only into one direction throughout your HTML document and thus avoid the possibility of collapsing margins at all.

This results in a nice fiddle showing an accordion menu without jumpy motion. I tried to obey the rule and only use margins into bottom direction, what works well. I used padding settings where possible compensate the missing margin-top setting.

A more simple fiddle without borders around the accordion content can be found here.

Author: Michael Keutel | 7.12.2015

2 Responses so far.

  1. Thomas sagt:

    Hey Mac,

    nice work! I like it.


  2. Michbeck sagt:

    Hey Thomas, thx! Stay tuned!