rufus rufus - 3 months ago 9
CSS Question

Image overflowing div advice

Im sure this is really easy but i have been looking at this issue for a little while and my brain has gone blank. I have a div that then has an image inside of it. The image seems to just overflow the div border and its driving me mad. I have an image below to show you what is happening along with the css.

image



#avatar {
float: left;
width: 50%;
height: 300px;
border: 1px solid black;
}

#avatar img {
width: 100%;
height: auto;
}

<div id="avatar">
<img src="http://i.imgur.com/dkzoNCc.png"></div>





I have a border on the main div #avatar just so i can see the whole size of the div. All i want is for the image to scale to the size of the div. If i set the height to 100% it goes into the div just fine but when resizing it it starts to overflow the div. I want the image to resize on the width not height.

Am i missing something really simple here? I dont want to use overflow hidden on the image as that will just cut some of it off i believe.

Thanks everyone

Answer

Try below css for img.

  • use height: 100%; for maximum height
  • display: block;margin: auto; for centering
  • max-width: 100%; to fit large images

Please check the example with large and small images.

#avatar {
  float: left;
  width: 50%;
  height: 300px;
  border: 1px solid black;
}
#avatar img {
height: 100%;
max-width: 100%;
display: block;
margin: auto;
}
<div id="avatar">
  <img src="http://www.baraodasfestas.com.br/Assets/Produtos/SuperZoom/0431_MICKEY_635703672330071491.jpg" alt="">
</div>
<div id="avatar">
  <img src="https://upload.wikimedia.org/wikipedia/en/d/d4/Mickey_Mouse.png" alt="">
</div>