1

I have web page with number of listings. Listing includes an image that comes in any size and width and height of the DIV that wraps the image is fixed. How can i fill the image in that DIV.

<div class="image-wrap" style="width:150px;height:150px;">
<img src="some-image.png">
</div>

enter image description here

jojo83thomas
  • 45
  • 1
  • 5

2 Answers2

1

If you are stuck to the HTML structure as place in the OP and you are open for a jQuery solution, you could use this code:

I've added comments in the code to clarify it.

$(function() {
  $('div').each(function() {
    var img = $(this).find('img'), /* find the image inside the div */
        imgUrl = img.attr('src'); /* get the image url */
    $(this).css('background-image', 'url('+imgUrl+')'); /* set the background image */
    img.remove(); /* remove the image inside the div */
  });
});
div {
  border: 1px solid red;
  margin: 1em;
  background-position: 50% 50%; /* center background image */
  background-size: cover; /* make the bg cover the whole element */
}

.div1 {
  width: 250px;
  height: 150px;
}

.div2 {
  width: 250px;
  height: 150px;
}

.div3 {
  width: 100px;
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div1">
  <img src="http://via.placeholder.com/350x150">
</div>
<div class="div2">
  <img src="http://via.placeholder.com/250x300">
</div>
<div class="div3">
  <img src="http://via.placeholder.com/350x150">
</div>
GreyRoofPigeon
  • 17,833
  • 4
  • 36
  • 59
-1

You can use bootstrap classes to achieve this. Use some col-md-4 based on your div size requirement and inside image tag you can add img-responsive class.

Else with default css like below. Hope this helps.

img {
max-width: 100%;
height: auto; }
Lilly
  • 1
  • 1