Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get width of a div in percentage using jQuery? [duplicate]

Tags:

jquery

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

like image 918
sun Avatar asked Sep 13 '13 12:09

sun


People also ask

How to get div width in percentage in jQuery?

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

How can set width percentage in jQuery?

width("20%") however the element kept getting set to width: 24% . After digging through the docs, turns out this is related to the CSS box-sizing property. Using . css({'width':"20%"}) will avoid this adjustment.

How do you measure the width of a div?

To measure the width of a div element we will utilize the offsetWidth property of JavaScript. This property of JavaScript returns an integer representing the layout width of an element and is measured in pixels. Return Value: Returns the corresponding element's layout pixel width.

What is the difference between width () vs CSS width in jQuery?

css('width') returns the attribute with the unit appended while . width() does not, it will give you the number in pixels. So if you have an element with a width of 200px . css('width') will return "200px" while .


1 Answers

To use your example code...

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

Working jsfiddle...

like image 183
Reinstate Monica Cellio Avatar answered Oct 12 '22 10:10

Reinstate Monica Cellio