14

I discovered something weird yesterday when working with a piece of JS code. I had a div that was hidden (display:none), and I was using the height of it in some calculations in JS. This was all working fine, until I added my "hidden" class (which has display:none !important).

Suddenly the height was always 0. There were no other changes than !important on the display.

After some digging I've narrowed the problem down to something I find rather weird:

#b { display:none; }            /* reported height is 36 */
#c { display:none !important; } /* reported height is 0  */

I've created a very basic JSFiddle to isolate this. It also uses vanilla JS to get height, which seems to work just fine / as expected.

It seems like jQuery incorrectly reports height on invisible DIVs, and that !important behaves correctly.

Is this a bug in jQuery?

Hashem Qolami
  • 97,268
  • 26
  • 150
  • 164
Eirik Hoem
  • 1,310
  • 7
  • 14
  • Most likely your `display: none;` without `!important` gets overruled. Display none should indeed return 0 – timo Feb 25 '14 at 08:37
  • possible duplicate of [jQuery: height()/width() and "display:none"](http://stackoverflow.com/questions/3632120/jquery-height-width-and-displaynone) – DAC84 Feb 25 '14 at 08:37
  • @user3008011 No, see the fiddle. – Eirik Hoem Feb 25 '14 at 08:38
  • @DAC84 That does not cover the !important usage – Eirik Hoem Feb 25 '14 at 08:41
  • If you manually set a height, it reports it. http://jsfiddle.net/kZ3ee/6/ – Derek Feb 25 '14 at 08:43
  • True, but it explains what is happening and worth linking to to save largely duplicating that answer. If you understand that !important overrides inline styles then you have the answer with that question. – DAC84 Feb 25 '14 at 08:45

1 Answers1

14

I dont think this is a bug in jQuery, jQuery sets display to block for a fraction of a second to calculate height, when you set !important even that is ovverriden, thats all.

I guess we need some more explanation

There is basically no way to get the height of an element from DOM if it doesn't have any height. So when display is none, the height is nonexistent or zero.

In jQuery if display is none, we can just set display to block for a fraction of a second to get the height, during this inline style is altered as usually done by jQuery.

<div id="something" style="display:block">/div>

And then height is taken, but at this time if you have set display:none!important in css this inline style wont work, and height calculated becomes zero.

In my personal opinion its always better not to use !important as it makes your code/presentation hard to read. Css usually has multitude of ways to override styles.

If you still want to proceed, an inline !important might override your style, and calculate the height by yourself using the jQuery show for a second technique, or just override the jQuery function to calculate height :)

sabithpocker
  • 15,274
  • 1
  • 42
  • 75