English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

jQuery width() Method

jQuery HTML/CSS Methods

The width() method gets or sets the width of the selected element.

When using the width() methodGetWhen setting the width, it will returnThe first selected elementwidth.

When using the width() methodSetWhen setting the width, it will setAll selected elementswidth.

As shown in the figure below, the width() method does not include padding, border, or margin:

The width value can also be relative. If a leading+=-If a character sequence = is provided, the target width is calculated by adding or subtracting the given number from the current value (for example, width("-= 250”)。

Syntax:

Get width:

$(selector).width()

Set width:

$(selector).width(value)

Set width using a function:

$(selector).width(function(index, currentWidth))

Example

Get the width of the DIV element:

$("div").click(function(){
  $(this).width();
});
Test and see‹/›

Set the width of all paragraphs:

$("button").click(function(){
  $("p").width(250);
});
Test and see‹/›

Set the width of all paragraphs using different units:

$("#btn1").click(function(){
  $("p").width(250);
});
$("#btn2").click(function(){
  $("p").width("7em");
});
$("#btn3").click(function(){
  $("p").width("100vw");
});
Test and see‹/›

Decrease the width of all paragraphs when the button is clicked (using a function):

$("button").click(function(){
  $("p").width(function(i, val){
        return val - 50;
  });
});
Test and see‹/›

The width() method can also find the width of the window and document:

$(window).width();// Return the width of the browser viewport:
$(document).width();  //Return the width of the HTML document:
Test and see‹/›

Display the differences between width(), height(), innerHeight(), innerWidth(), outerWidth(), and outerHeight():

$("button").click(function(){
  $("div").width();
  $("div").innerWidth();
  $("div").outerWidth();
  $("div").height();
  $("div").innerHeight();
  $("div").outerHeight();
});
Test and see‹/›

Parameter Value

ParameterDescription
valueAn integer representing pixel numbers, or an integer appended with an optional measurement unit (as a string)
function(index, currentWidth)Specify a function that returns the width of the selected element
  • index-Return the index position of the element in the collection

  • currentWidth-Return the current width of the selected element

jQuery HTML/CSS Methods