简体   繁体   中英

!important and display:none and .height() weirdness

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?

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM