开发者

Setting width as a percentage using jQuery

开发者 https://www.devze.com 2022-12-17 03:10 出处:网络
How can I set the width of a div as a percentage 开发者_如何学JAVAusing jQuery?Using the width function:

How can I set the width of a div as a percentage 开发者_如何学JAVAusing jQuery?


Using the width function:

$('div#somediv').width('70%');

will turn:

<div id="somediv" />

into:

<div id="somediv" style="width: 70%;"/>


Here is an alternative that worked for me:

$('div#somediv').css({'width': '70%'});


Hemnath

If your variable is the percentage:

var myWidth = 70;
$('div#somediv').width(myWidth + '%');

If your variable is in pixels, and you want the percentage it take up of the parent:

var myWidth = 140;
var myPercentage = (myWidth / $('div#somediv').parent().width()) * 100;
$('div#somediv').width(myPercentage + '%');
0

精彩评论

暂无评论...
验证码 换一张
取 消