Search code examples
htmlcssimagebackground-imagebackground-size

How to achieve "background-image: cover" CSS effect for dynamic images?


When using the following CSS style, an image covers a div completely, while preserve its proportions:

div {
  background: url(images/plants/flower.jpg);
  background-size: cover;
  background-repeat: no-repeat;
}

The problem is that I need to generate the image URL using PHP and therefore I can't specify it in the CSS property.

I prefer not to use jQuery, JavaScript or inline CSS. The code I am after looks like this:

PHP

$img_url = get_img_url();
echo '<div><img src="' . $img_url . '"></div>';

CSS

 div {
  width: 600px;
  height: 200px;
}
img {
  size: cover;
}

Solution

  • I ended up doing the following, without altering the html nor using other language:

    PHP

    $img_url = get_img_url();
    

    HTML

    <div>
      <img src="<?php echo $img_url; ?>">
    </div>
    

    CSS

    div {
      width: 600px;
      height: 200px;
    }
    
    div img {
      min-width: 100%;
      min-height: 100%;
    }