1

If I alert the element which has a css selector set to width:100% I get it's with in px, is there some way to get it in % as set from css, I need it to fix some script with fluid layouts.

// css
.my-element {
    width:100%;
}

// javascript
alert('width: '+$('.my-element').css('width'));
// this alerts "width: 1116px" instead of "width: 100%"

Maybe something like this is always true?

alert($('.my-element').outerWidth() == $('.my-element').parent().outerWidth());
vitto
  • 19,094
  • 31
  • 91
  • 130
  • There is a plugin which I forgot it's name that read css properties from the `css` file... :( – gdoron May 16 '12 at 18:23
  • 2
    interesting! I never thought to need the with in `%` I think this should a useful feature for fluid layouts. – vitto May 16 '12 at 18:27

3 Answers3

6
function percentwidth(elem){
    var pa= elem.offsetParent || elem;
    return ((elem.offsetWidth/pa.offsetWidth)*100).toFixed(2)+'%';
}
kennebec
  • 102,654
  • 32
  • 106
  • 127
4

You can get the width in percentage by two methods.

Live Demo

With jQuery use jQuery 1.3.2 and you will get 100%.

alert($('.my-element').css('width'))​;

With javascript by setting width in style attribute of the tag like this

<div id="div2" style="width:100%"></div>

div2 = document.getElementById('div2');

alert("Width of div2 with style = " + div2.style.width);
Adil
  • 146,340
  • 25
  • 209
  • 204
-1

This post

Is it possible to use jQuery to get the width of an element in percent or pixels, based on what the developer specified with CSS?

Community
  • 1
  • 1
Mike Boutin
  • 5,297
  • 12
  • 38
  • 65