jQuery CSS Operation - width() Method

Example

Set the width of the <p> element:

$(".btn1").click(function(){
  $("p").width(200);
});

Try it yourself

Definition and Usage

The width() method returns or sets the width of the matching elements.

Return width

Returns the width of the first matching element.

If no parameters are set for this method, it returns the width of the matching elements in pixels.

Syntax

$(selector).width()

Try it yourself

Set width

Sets the width of all matching elements.

Syntax

$(selector).width(length)
Parameters Description
length

Optional. Specifies the width of the element.

If no length unit is specified, the default px unit is used.

Try it yourself

Use a function to set width

Use a function to set the width of all matching elements.

Syntax

$(selector).width(function(index,oldwidth))
Parameters Description
function(index,oldwidth)

Specifies a function that returns the new width of the selected elements.

  • index - Optional. Accepts the index position of the selector
  • oldvalue - Optional. Accepts the current value of the selector.

Try it yourself

More examples

Get the width of the document and window elements
Use the width() method to get the current width of the document and window elements.
Set width using em and % values
Set the width of the element using the specified length unit.