Languages
[Edit]
EN

CSS - stretch background image to element size

0 points
Created by:
Giles-Whittaker
739

In this article, we would like to show you how to stretch background image to element size with CSS.

 

PreviewStyle

background-size: 100% 100%

Note:

The image is stretched to the entire surface of the element, losing the ratio.

background-size: cover

Note:

The image is stretched to the entire surface of the element keeping the ratio.

background-size: contain

Note:

The image is stretched to the entire surface of the element keeping the ratio (by default the image is repeated).

  • background-size: contain;
  • background-repeat: no-repeat;

Practical example

In this example, we present different ways to stretch background image to element size, depending on the effect you want to achieve.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    div  {
      margin: 3px;
      border: 1px solid black; 
      background-image: url("https://dirask.com/static/bucket/1631898942509-VMYrnXyYZv--image.png");
    }
    
    .stretch {
      background-size: 100% 100%;  /*  background-size: width height  */;
    }
    
    .cover { background-size: cover; }

    .contain { background-size: contain; }
    
    .contain-norepeat {
      background-size: contain;
      background-repeat: no-repeat;
    }

  </style>
</head>
<body>
  <p>stretch - height and width = 100%:</p>
  <div class="stretch" style="width: 150px; height: 100px;"></div>
  <div class="stretch" style="width: 100px; height: 150px;"></div>
  <p>cover:</p>
  <div class="cover" style="width: 150px; height: 100px;"></div>
  <div class="cover" style="width: 100px; height: 150px;"></div>
  <p>contain:</p>
  <div class="contain" style="width: 150px; height: 100px;"></div>
  <div class="contain" style="width: 100px; height: 150px;"></div>
  <p>contain with no-repeat:</p>
  <div class="contain-norepeat" style="width: 150px; height: 100px;"></div>
  <div class="contain-norepeat" style="width: 100px; height: 150px;"></div>
</body>
</html>

References

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join