Jesus BC Jesus BC - 5 months ago 19
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 {
max-width:80%;
}


jQuery -> .contain is in %!

.contain {
max-width:80px;
}


jQuery -> .contain is in px!

Thx!

Answer

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.

console.log($('div').css('max-width'));
console.log($('div').css('width'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="width: 80%; max-width: 80%">
  Bananas
</div>

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