Snorlax February 2016

Resize image according to div width

I have a div width that resizes according to the browser width, right now it is set to 80%.

What I'm trying to accomplish is depending on the image size, I would like the image to take up the whole div width. If it's a small image, keep image size and center.

In my fiddle, any image width over 800px should start from the right and expand according to the div re-size. It should always touch the right side and expand with the div width.

If the image width is smaller than or equal to 500px, it should stay it's size and resize according to div but stay in middle of div only.

The problem is, I'm not sure how to only affect certain images, I would like a solution that detects the image size because the images might switch.

.parent{
  border:1px solid purple;
  height:100%;
  width:80%;
  float:Right;
}
.child{
  border:1px solid red;
  height:100%;
  background:gray;
  text-align:center;
}
.child-img{
display:inline-block;
max-width:100%;
margin:0 auto;
}
.image-wrapper{
  width:100%;
  background:orange;
}
img{
width:auto;
height:100%;
width:100%;
}
<div class="parent">
  <div class="child">
  <div class="image-wrapper">
    <img src="http://cdn.bulbagarden.net/upload/thumb/0/0d/025Pikachu.png/250px-025Pikachu.png" alt="" class="child-img">
        </div>
        <div class="image-wrapper">
        <img src="https://i.kinja-img.com/gawker-media/image/upload/unnbgkdbmsszmazgxkmr.jpg" alt="" class="child-img">
        </div>
        <div class="image-wrapper">
            <img src="https://em.wattpad.com/62f9f1c9de49ad97d7834b1e58e16a99eb2dc3c7/687474703a2f2f6170692e6e696e672e63        

Answers


Farzad YZ February 2016

Try using jQuery to detect the image's size.

$('.child-img').each(function() {
  if ($(this).width() > 800) { $(this).addClass('right'); }
  else if ($(this).width() < 500) {$(this).addClass('center');}
});

And the required css would be:

.child-img.right {
  display: block;
  max-width: 100%;
}
.child-image.center {
  width: auto;
 max-width: 100%;
 display: inline-block'
}
.parent { text-align: center; }


rotato poti February 2016

I think you should be able to place the image in the background of the div and make its width and height percentage values.

background: url(img_flwr.gif);
background-size: 100% 100%;
background-repeat: no-repeat;

Post Status

Asked in February 2016
Viewed 2,206 times
Voted 8
Answered 2 times

Search




Leave an answer