Javascript Reference - HTML DOM Style backgroundSize Property








The backgroundSize property sets or gets the size of the background images.

Browser Support

backgroundSize Yes 10 Yes Yes Yes

Syntax

Return the backgroundSize property:

var v = object.style.backgroundSize 

Set the backgroundSize property:

object.style.backgroundSize='auto|length|cover|contain|intial|inherit'

Property Values

The background-size Values:

ValueDescription
lengthSets the width/height of the background image.
The first value is width, the second value is height.
Missing value is default to "auto".
Negative lengths are not allowed.
percentage Sets the width/ height of the background image in percent of the container.
The first value is width, the second value is height.
Missing value is default to "auto".
Negative percentages are not allowed.
containScales the image, preserving the aspect ratio, to the largest size that can fit.
coverScales the image, preserving the aspect ratio, to the smallest size that can fit.
autoDisplay the image at full size(default).




Technical Details

Default Value: auto
Return Value: A string representing the background-size property
CSS Version CSS3

Example

The following code shows how to set the size of a background image.


<!DOCTYPE html>
<html>
<head>
<style> 
#myDIV {<!--from  www .j  av a  2  s.c o m-->
    border: 1px solid black;
    width: 300px;
    height: 300px;
    background: url('http://java2s.com/style/demo/border.png') no-repeat;
}
</style>
</head>
<body>
<button onclick="myFunction()">test</button>
<div id="myDIV">Hello</div>
<script>
function myFunction() {
    document.getElementById("myDIV").style.backgroundSize = "60px 120px";
}
</script>
</body>
</html>

The code above is rendered as follows: