Interview Questions

Why do animations set the display style to block?

jQuery Interview Questions and Answers


(Continued from previous question...)

Why do animations set the display style to block?

Only block-level elements can have a custom width or height. When you do an animation on an element that animates the height or width (such as show, hide, slideUp, or slideDown), the display CSS property will be set to 'block' for the duration of the animation. The display property will be reverted to its original value after the animation completes. (This does not work properly for inline-block elements.)

There are two common workarounds:

If you want the element to stay inline, but you just want it to animate in or out, you can use the fadeIn or fadeOut animations instead (which only affect the opacity of an element).

// Instead of this:
$("span").show("slow");

// do this:
$("span").fadeIn("slow");

The other option is to use a block-level element, but to add a float such that it appears to stay inline with the rest of the content around it. The result might looks something like this:

// A floated block element

...


// Your code:
$("div").show("slow");

Other Interview Questions