Reputation: 59
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!
Upvotes: 2
Views: 516
Reputation: 28475
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.)
Upvotes: 2
Reputation: 33933
Citation from the jQuery .css()
page.
«The .css() method is a convenient way to get a computed style property (...)»
«Note that the computed style of an element may not be the same as the value specified for that element in a style sheet. For example, computed styles of dimensions are almost always pixels, but they can be specified as em, ex, px or % in a style sheet.»
Here is a test Fiddle working with the latest jQuery version (3.0.0).
So... Simple answer is no.
Upvotes: 0
Reputation: 5146
$('.contain').css('max-width')
It will return you a String, either "80px" either "80%"
Then you can use indexOf to find if there is "px" or "%"
if ($('.contain').css('max-width').indexOf("px") !== -1) {
//is in px
} else if ($('.contain').css('max-width').indexOf("%") !== -1) {
//is in %
}
Upvotes: 3