Freddy
Freddy

Reputation: 857

Resizing an image so that it fits in it's container

I have a div profile_pic which has the following CSS:

#profile_pic{
    position:absolute;
    border:1px solid #E1E3E4;
    left:25px;
    top: 25px;
    width: 200px;
    height: 200px;  
}

Since profile picture for my application can be any image (of any size), the div or image, should be flexible to adapt to one another. I have tested a profile picture with the dimensions of 300px width and 300px height and the image renders perfectly in the the div. However, when I upload a picture with say, 550px width and 400px width the image is appearing "squashed" which is understandable.

There are two options, 1. resizing the image so that the whole image appears in the div and 2. cropping the image so that the image adapts to the div size. I do not mind adopting either of these approaches but I am unable to implement how these approaches in code.

I have tried to set:

#profile_pic {width: 50%}
#profile_pic img {width:100%}

But it just does not work. How can I get the div (or image) to always fit in the div's size without the image losing it's quality?

Upvotes: 0

Views: 424

Answers (2)

WelshBoyZz
WelshBoyZz

Reputation: 84

You could just add background-size:contain; to the div that has the image (assuming you are setting the background image the image you want.

losing quality is another thing, scaling say a 50x50px image to 100x100 is going to lose quality, so it would probably be best to set a minimum size the profile picture can be.

Upvotes: 2

G-Cyrillus
G-Cyrillus

Reputation: 105853

You may set max-width and max-height in order to resize image to fit inside the box without overflow, add line-height and text align to center image in case it has not the same box ratio.

#profile_pic,
.profile_pic2 {
  position: absolute;
  border: 1px solid #E1E3E4;
  left: 25px;
  top: 25px;
  width: 200px;
  height: 200px;
  line-height: 197px;
  /* since image is the one and  single child */
  text-align: center;
  border: solid;
  /*demo purpose */
}
.profile_pic2 {
  left: 250px;
}
.profile_pic2 +.profile_pic2 {
  left: 450px;
} 
#profile_pic img, .profile_pic2 img {
  max-width: 100%;
  max-height: 100%;
  vertical-align: middle;
  /* set on middle baseline setted at 200px */
}
<div id="profile_pic">
  <img src="//lorempixel.com/640/480">
</div>
<div class="profile_pic2">
  <img src="//lorempixel.com/480/640">
</div>
<div class="profile_pic2">
  <img src="//lorempixel.com/480/480">
</div>

Upvotes: 0

Related Questions