Languages
[Edit]
EN

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

6 points
Created by:
Root-ssh
175340

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:

Alternative titles

  1. CSS - position image in div filling / covering all available space keeping image ratio
  2. CSS - image size to cover div container with centering inside div
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.

CSS

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