/

HTML / CSS / JavaScript Tutorial

CSS Property: background-size

[this page | pdf | back links]

The CSS (CSS3) background-size property specifies the size of the background image(s).

 

Valid property values (other than inherit and initial) are:

 

Value

Description

auto

(default value). Background-image contains its width and height

contain

Scales the image to be as large as possible such that both width and height fit inside the content area

cover

Scales the image to be as large as possible to cover the background area completely

length

Sets width and height in that order using any valid CSS length. If only one is given the second is set to auto

percentage

Sets width and height in that order as percentages of the parent element. If only one is given the second is set to auto

 

Default Value:

auto

JavaScript syntax:

e.g. object.style.backgroundSize="60px 80px"

Inherited:

No

Animatable:

Yes

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
p {width: 200px; background-image: url(NematrianLogo.png); padding: 20px;}
p.x1 {background-size: contain;}
</style>
</head>
<body>
1. Element with default property<br>
<p>1</p><br>
2. Element set using in-file HTML style
<p class="x1">2</p><br>
3. Element set using JavaScript
<p id="x2">3</p>

<script>
document.getElementById("x2").style.backgroundSize =
  "contain";
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedCSSPropertyBackgroundSize() {
  var x = document.createElement("DIV"); x.style.backgroundSize = "contain"; return (window.getComputedStyle(x, null).backgroundSize == "contain");
}


NAVIGATION LINKS
Contents | Prev | Next | CSS Properties


Desktop view | Switch to Mobile