CSS background-size

The CSS background-size property is used to define the size of background-image. For example:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      #myd{border: 3px solid chocolate; padding: 22px;
         background-image: url("images/usml-plnt-lf.jpg");
         background-repeat: no-repeat;
         background-size: 100px 50px;}
   </style>
</head>
<body>
   
   <div id="myd">
      <h2>The background-size Property</h2>
      <p>This is an example of background-size property.</p>
   </div>
   
</body>
</html>
Output

The background-size Property

This is an example of background-size property.

The actual size of image used as background in above example, is 160*97. But I've customized the size to 100*50. That is, the first value refers to width and the second value refers to height, of the image.

CSS background-size Syntax

The syntax of background-size property in CSS, is:

background-size: x;

The x refers to single or multiple values, and should be any of the following:

Note - If two values are given, then first value refers to the width, whereas the second value refers to the height of the background image.

Note - In case of percentage and length, if only one value given to background-size, then second value automatically set to auto.

CSS background-size Example

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      #a, #b, #c, #d, #e, #f{border: 3px solid chocolate;
         height: 200px; padding: 22px; margin-bottom: 20px;
         background-image: url("images/usml-plnt-lf.jpg");
         background-repeat: no-repeat;}
      #a{background-size: auto;}
      #b{background-size: 80% 30%;}
      #c{background-size: 100px 30px;}
      #d{background-size: 100px;}
      #e{background-size: cover;}
      #f{background-size: contain;}
   </style>
</head>
<body>
   
   <h3>background-size: auto</h3>
   <div id="a"></div>

   <h3>background-size: 80% 30%</h3>
   <div id="b"></div>

   <h3>background-size: 100px 30px</h3>
   <div id="c"></div>

   <h3>background-size: 100px</h3>
   <div id="d"></div>

   <h3>background-size: cover</h3>
   <div id="e"></div>

   <h3>background-size: contain</h3>
   <div id="f"></div>
   
</body>
</html>
Output

background-size: auto

background-size: 80% 30%

background-size: 100px 30px

background-size: 100px

background-size: cover

background-size: contain

CSS Online Test


« Previous Tutorial Next Tutorial »