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
var percent = $('. f'). width() / $('body'). width() * 100; console.
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.
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.
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 .
To use your example code...
$(document).ready(function(){
var f = $(".f").width() / $('.f').parent().width() * 100;
alert(f);
});
Working jsfiddle...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With