CSS Property background-size








You can specify percentages and pre-defined values for background-image size. The size is then derived from the width and height of the image.

Summary

Initial value
auto
Inherited
no
CSS Version
CSS3
JavaScript syntax
object.style.backgroundSize="100px 120px"
Animatable
Yes

CSS Syntax

background-size: auto|length|cover|contain|initial|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).




Browser compatibility

background-size Yes Yes Yes Yes Yes

Example

Set background image size to contain:

<!DOCTYPE HTML> 
<html> 
    <head> 
        <title>Example</title> 
        <style type="text/css"> 
        p { <!--  ww  w  .j  a v  a2 s . c  o  m-->
            background-image: url(http://java2s.com/style/download.png); 
            background-repeat: repeat-x; 
            background-size:contain; 
        } 
        </style> 
    </head> 
    <body> 
        <p> 
            HyperText Markup Language (HTML) is the main markup language for 
            displaying web pages and other information that can be displayed 
            in a web browser(From From Wikipedia, the free encyclopedia).
        </p> 
    </body> 
</html>

Click to view the demo





Example 2

Set background image size to cover:

<!DOCTYPE HTML> 
<html> 
    <head> 
        <title>Example</title> 
        <style type="text/css"> 
        p { <!--from w ww.  j  av a 2  s .  c o  m-->
            background-image: url(http://java2s.com/style/download.png); 
            background-repeat: repeat-x; 
            background-size:cover; 
        } 
        </style> 
    </head> 
    <body> 
        <p> 
            HyperText Markup Language (HTML) is the main markup language for 
            displaying web pages and other information that can be displayed 
            in a web browser(From From Wikipedia, the free encyclopedia).
        </p> 
    </body> 
</html>

Click to view the demo