Javascript DOM CSS Style backgroundSize Property

Introduction

Specify the size of a background image:

document.getElementById("myDIV").style.backgroundSize = "60px 120px";

Click the button to enlarge the background-size of the DIV element:

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {// w ww .  ja v a  2 s  .c om
  border: 1px solid black;
  width: 300px;
  height: 300px;
  background: url('background2.png') no-repeat;
}
</style>
</head>
<body>
<button onclick="myFunction()">Test</button>

<div id="myDIV">
  <h1>Hello</h1>
</div>

<script>
function myFunction() {
  document.getElementById("myDIV").style.backgroundSize = "60px 120px";
}
</script>

</body>
</html>

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

Property Values

Value
Description
auto
Default. The background-image contains its width and height
length


Sets the width and height of the background image.
The first value sets the width, the second value sets the height.
If only one value is given, the second is set to "auto"
percentage


Sets the width and height of the background image in percent of the parent element.
The first value sets the width, the second value sets the height.
If only one value is given, the second is set to "auto"
cover
Scale the background image to cover.
contain
Scale the image to fit both its width and its height inside the content area
initial
Sets this property to its default value.
inherit
Inherits this property from its parent element.

The backgroundSize property returns a String representing the background-size property of an element.




PreviousNext

Related