Setting width as a percentage using jQuery

JqueryWidth

Jquery Problem Overview


How can I set the width of a div as a percentage using jQuery?

Jquery Solutions


Solution 1 - Jquery

Using the width function:

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

will turn:

<div id="somediv" />

into:

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

Solution 2 - Jquery

Here is an alternative that worked for me:

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

Solution 3 - Jquery

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 + '%');

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPrasadView Question on Stackoverflow
Solution 1 - JqueryDarin DimitrovView Answer on Stackoverflow
Solution 2 - Jqueryjoaorodr84View Answer on Stackoverflow
Solution 3 - JqueryJonathan ElderView Answer on Stackoverflow