Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if width has px or %

How can i tell if a css property such as width ex: width:100% has px or % assigned to it. in chrome for example if i have width:250px; and i do $('div').width() i get 250 whereas if i use percentage, i just get the width in px for the percentage based on my screen resolution.

like image 758
Pinkie Avatar asked Oct 16 '11 20:10

Pinkie


3 Answers

This should work.

var value = $('#id').get(0).style.width;
var hasPx = value.indexOf('px') >= 0;
var hasPct = value.indexOf('%') >= 0;

JSBin: http://jsbin.com/asewit/2/edit#javascript,html

like image 152
Sajid Avatar answered Nov 01 '22 09:11

Sajid


If by "css property" you mean css rule, and not inline style property set directly in the element, there is no fast way to get it. You'd have to:

  1. Query all css rule declarations

  2. Loop through every css rule and check if the element matches the rule and push it into array

  3. Loop through the candidates and take the latest width value, or the latest width value with !important

If you mean inline style, it's so trivial it's hard to understand why the question got so many upvotes:

element.style.width and check if there is a px or % there

edit: here is incomplete demo for the css rule querying:

http://jsfiddle.net/Chjnd/1/

tested in google chrome and firefox

like image 9
Esailija Avatar answered Nov 01 '22 09:11

Esailija


You can use .style.cssText, which contains the actual CSS code:

$("<div style='width:50px'>").get(0).style.cssText // "width: 50px; "
$("<div style='width:50% '>").get(0).style.cssText // "width: 50%; "
like image 3
pimvdb Avatar answered Nov 01 '22 07:11

pimvdb