Languages
[Edit]
EN

CSS - fill / cover with image all div keeping image ratio

3 points
Created by:
Root-ssh
7587

In this article we are going to show how in CSS fill with image all div to cover all available space keeping image ratio. 

Note: for JavaScript version with img element read this article.

CSS styling example

In this section we cover all available div space with image keeping the image ratio.

Useful style property for filling is background-size: cover; 

Note: it is important to set size for div element.

// ONLINE-RUNNER:browser;

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

    #image1 {
      border: 1px solid red;
      background-repeat: no-repeat;
      background-size: cover; /* <-------------- required */
      background-position: 50%; /* <------------ required */
      background-image: url('https://dirask.com/static/bucket/1590005168287-pPLQqVWYa9--image.png'); /* <--- required */
      width: 120px; /* <------------------------ required */
      height: 200px; /* <----------------------- required */
    }
    
    #image2 {
      border: 1px solid red;
      background-repeat: no-repeat;
      background-size: cover; /* <-------------- required */
      background-position: 50%; /* <------------ required */
      background-image: url('https://dirask.com/static/bucket/1590005168287-pPLQqVWYa9--image.png'); /* <--- required */
      width: 300px; /* <------------------------ required */
      height: 120px; /* <----------------------- required */
    }

  </style>
</head>
<body>
  <div id="image1"></div>
  <br />
  <div id="image2"></div>
</body>
</html>

Used resource:

Hey 👋
Would you like to know what we do?
  • Dirask is online IT community for professionals and hobbyist to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.