18

I have a div, and I'd like to know if there's a way to get its width in percentage using jQuery.

Here's my code:

$(document).ready(function(){
   var f = $('.f').width();
      alert(f);    
});

I tried to use % as an argument like this width(%), but this is setting the width as % not getting the value in a percentage format. Can someone tell me what should I do to get in percentage instead?

Any help is profusely appreciated.

Fiddle

Kyle
  • 1,568
  • 2
  • 20
  • 46
sun
  • 1,598
  • 11
  • 26
  • 45
  • Width is only ever given as an absolute value in pixels. To convert this to `%` you need to get the width of the parent element and do some maths. – Rory McCrossan Sep 13 '13 at 12:10

4 Answers4

46

To use your example code...

$(document).ready(function(){
   var f = $(".f").width() / $('.f').parent().width() * 100;
   alert(f);    
});

Working jsfiddle...

Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67
7

If you want the width relative to the body:

var percent =  $('.f').width() / $('body').width() * 100;

console.log(Math.round(percent).toFixed(2)); 

Is this what you're asking for?

http://jsfiddle.net/aXRxP/5/

Johan
  • 35,120
  • 54
  • 178
  • 293
1

you will need to get viewport width and then calculate your element width percentage in accordance with viewport width.

var width = $('#someElt').width();
var parentWidth = $('#someElt').offsetParent().width(); // this will return parent element's width which also can be replaced with docuent to get viewport width
var percent = 100*width/parentWidth;
Ganesh Pandhere
  • 1,612
  • 8
  • 11
0
$(document).ready(function(){
   var f = $('.f').width();
    var pw = $('.f').parent().width();
    var rate = (f/pw*100) + '%';
    $('.f').html( rate);    
});

it is parent item's with. So if you rate the .f div's width to parent item's width you get that value.

zkanoca
  • 9,664
  • 9
  • 50
  • 94