Javascript Reference - HTML DOM Style width Property








The width property in CSS controls width for block-level elements or on elements with absolute or fixed position.

The width property sets or gets the element's width.

Browser Support

width Yes Yes Yes Yes Yes

Syntax

Return the width property:

var v = object.style.width 

Set the width property:

object.style.width='auto|length|%|initial|inherit'

Property Values

Value Description
auto Let browser decide. Default
length Set the width in length units
% Set the width in percent of the container element
initial Set to default value
inherit Inherit from parent element.




Technical Details

Default Value: auto
Return Value: A string representing the width of an element
CSS Version CSS1

Example

The following code shows how to set the width of an element.


<!DOCTYPE html>
<html>
<body>
<!--from   w w  w .ja  v a2  s  .c  o m-->
<button type="button" id="myBtn" onclick="myFunction()">test</button>

<script>
function myFunction() {
    document.getElementById("myBtn").style.width = "300px";
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 3

The following code shows how to change the height and width of an <img> element.


<!DOCTYPE html>
<html>
<body>
<!--from  www  . j  av  a2s  .c  o m-->
<img id="myImg" src="http://java2s.com/style/demo/border.png" width="100" height="132">
<br>

<button type="button" onclick="myFunction()">test</button>

<script>
function myFunction() {
    document.getElementById("myImg").style.height = "300px";
    document.getElementById("myImg").style.width = "300px";
}
</script>

</body>
</html>

The code above is rendered as follows:

Example 4

The following code shows how to get the width of an <img> element:


<!DOCTYPE html>
<html>
<body>
<img id="myImg" src="http://java2s.com/style/demo/border.png" style="width:100px;height:132px;">
<button type="button" onclick="myFunction()">test</button>
<!--from  w  w w .  j a va  2  s . c o m-->
<script>
function myFunction() {
    console.log(document.getElementById("myImg").style.width);
}
</script>

</body>
</html>

The code above is rendered as follows: