jQuery

jQuery Set Width in px, em, pt (Div, li, etc.)

In an earlier article, we have seen how we can get the width of an element, such as a div, li, etc. using jQuery. In this article, lets discuss how you can set the width in px(pixels), em, pt, etc. using jQuery The actual code to is just 1 line, so it’s super easy to follow along. Read on to find out more.


How to for Set the Width of any Element using jQuery?

jQuery provides us with a very simple method, called width(). So the basic syntax to set width of an element would be as follows:

jQuery Set element width

//value represents numerical value in pixels
$(selector).width(value);

//optionally you can specify the relative unit of measurement along with the value
$(selector).width("valuepx");

Example 1: Set div width using div ID – Set it to 50 pixels

$('#my_div').width(50);

//The code below produces the same output as the above code
$('#my_div').width("50px");

Example 2: Set div width using div class – Set it to 100 pixels

$('.my_div_class').width(100);

Example 3: Set li width – Set it to 75 pixels

$('ul li').width(75);

Example 4: Set width of a specific li – Set it to 18 pixels

$('li#list_item_1').width(18);

$('#list_item_1').width(18);

Example 5: Set paragraph width – Set it to 100 pixels

$('p').width(100);

If you have noticed something, all widths expressed are in pixels. What if you want to use another measurement alternative such as em, pt instead of pixels? Let’s see how we can do that.

Example 6: Set div width using div ID – Set it to 10 em

$('#my_div').width("10em");

Example 7: Set div width using div class – Set it to 1000 pt

$('.my_div_class').width("1000pt");
Your Turn!

Do you know of any other ways to set width of an element (li, div, etc.) using jQuery? Feel free to suggest by commenting below.

2 Comments on jQuery Set Width in px, em, pt (Div, li, etc.)

  1. 1

    You can also set the width of an element using the $.css() method which takes either a key value pair or an object of key value pairs.

    $( ‘#element’ ).css( ‘width’, 200 + ‘px’ );

    or

    $( ‘#element’ ).css({
    ‘width’ : 200 + ‘px’
    });

Share your thoughts, comment below now!

*

*