0

Simple fiddle - http://jsbin.com/mamenagu/1/edit
A more thorough fiddle - http://jsbin.com/mamenagu/7/edit

I'm working on an experimental website designer, and I ran into a problem grabbing element's css styles.

I noticed that when I set a css style to 80%. The browser retrieved it in a pixel form instead of a percentage based form.

Here's the code...

$(".montrer-largeur").html("width: " + $(".la-largeur").css('width'));

In addition when no padding, overflow, etc: is defined when I use that as the value to be retrieved I noticed it also grabbed the default value rather than leave it empty.

I know I can use the following code to grab an elements width via percentage (demo provided here)

var width = ( 100 * parseFloat($('.la-largeur').css('width')) / parseFloat($('.la-largeur').parent().css('width')) ) + '%';
$(".montrer-largeur").html(width);

However my problem is I don't want pixels being retrieved if the element's width is in a percentage based form, and I don't want to retrieve percents of the element's width is in pixels/em/etc: form

Does anyone know if there's a way to do this in JQuery?

Any help is greatly appreciated thanks.

Michael Schwartz
  • 8,153
  • 14
  • 81
  • 144
  • Possible answers: http://stackoverflow.com/questions/744319/get-css-rules-percentage-value-in-jquery –  Apr 04 '14 at 10:56

1 Answers1

1

There's no built-in way, I'm afraid. You can do something like this:

var width = ( 100 * parseFloat($('.la-largeur').css('width')) / parseFloat($('.la-largeur').parent().css('width')) ) + '%';

Working example here http://jsbin.com/mamenagu/2/

Dean Meehan
  • 2,511
  • 22
  • 36
  • So if I grab overflow when overflow has no set value defined it'll still give me the default. Is what you're saying? – Michael Schwartz Apr 04 '14 at 11:01
  • No? It gets the size of the container and divides it by the size of its parent container to get the % that way – Dean Meehan Apr 04 '14 at 11:04
  • I understand that, but my app doesn't just grab the selected elements width. I grab other elements as well. Which is what I'm trying to understand based upon your clarification. – Michael Schwartz Apr 04 '14 at 11:12