Languages
[Edit]
EN

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

3 points
Created by:
Root-ssh
6322

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.

background-size: cover; with image centering.

Note: it is important to provide div configuration to have size.

// ONLINE-RUNNER:browser;

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

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

  </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 a friendly IT community for learners, professionals and hobbyists 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.