Jesus BC Jesus BC - 2 years ago 125
jQuery Question

Need to know in jQuery if a max-width value is in % or px

There is some way in jQuery to know if the max-width value of a element defined in a css page is in % or px because jQuery always returns the value in px.

I mean....

.contain {

jQuery -> .contain is in %!

.contain {

jQuery -> .contain is in px!


Answer Source

The strange thing is that Louys Patrice Bessette and Mayday are both right.

Mayday's answer is correct... If you test it in Chrome! .css('width') will return in px (even if set in %), whereas .css('max-width') will return % when using that unit! In Firefox, however, the value is always px. You can test this with the code below and open in Firefox as well as Chrome.

<script src=""></script>
<div style="width: 80%; max-width: 80%">

By this we can say that Louys Patrice Bessette was right in poiting out that you cannot do this. That is true, if you are talking about jQuery's CSS method - and probably any getComputedStyle-like method.

What you can do, though, is parse the style sheet and read the actual value that is written in the styles. There are a number of other answers that deal with this, so check them out (you can use the search function to look for more):

Or you can simply read the CSS file as a text file, and then use regular expressions to find the value that you need. (However, this is probably slower or at least more error prone.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download